Created
May 29, 2018 17:22
-
-
Save iswanj/b2dcf16d1b298b9103e8f98bfa50128d to your computer and use it in GitHub Desktop.
Composing Functions
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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