Skip to content

Instantly share code, notes, and snippets.

@OttlikG
Last active February 4, 2018 10:56
Show Gist options
  • Save OttlikG/98a669a0afb63bc035d44eb90a61d4a1 to your computer and use it in GitHub Desktop.
Save OttlikG/98a669a0afb63bc035d44eb90a61d4a1 to your computer and use it in GitHub Desktop.
Functional programming
export const compose = (...fn) => fn.reduce((f, g) => (...arg) => f(g(...arg)));
export const curry = fn => {
const arity = fn.length;
return (...args) => {
const firstArgs = args.length;
if (firstArgs >= arity) {
return fn(...args);
}
return (...secondArgs) => {
return fn(...[...args, ...secondArgs]);
};
};
};
// Function composition OR
// import pipe from 'lodash/fp/flow';
const pipe = (...fns) => x => fns.reduce((y, f) => f(y), x);
// Functions to compose
const g = n => n + 1;
const f = n => n * 2;
// Imperative composition
const doStuffBadly = x => {
const afterG = g(x);
const afterF = f(afterG);
return afterF;
};
// Declarative composition
const doStuffBetter = pipe(g, f);
console.log(
doStuffBadly(20), // 42
doStuffBetter(20) // 42
);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment