Skip to content

Instantly share code, notes, and snippets.

@iswanj
Created May 29, 2018 17:22
Show Gist options
  • Save iswanj/b2dcf16d1b298b9103e8f98bfa50128d to your computer and use it in GitHub Desktop.
Save iswanj/b2dcf16d1b298b9103e8f98bfa50128d to your computer and use it in GitHub Desktop.
Composing Functions
function increment(x) { return x + 1; }
function decrement(x) { return x - 1; }
function double(x) { return x * 2; }
function half(x) { return x / 2; }
function compose(...fns) {
return pipe(...fns.reverse());
}
function pipe(...fns) {
return function(input) {
return fns.reduce((value, fn) => {
return fn(value);
}, input);
}
}
var f = compose(decrement,double,increment,half);
var p = pipe(half,increment,double,decrement);
console.log(f(3) === 4);
// true
console.log(f(3) === p(3));
// true
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment