-
-
Save robotlolita/ccecb9b6781ba085d142040a943e1a96 to your computer and use it in GitHub Desktop.
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 compose(first, second) { | |
return function(data) { | |
return second(first(data)); | |
} | |
} | |
function composeAll(functions) { | |
return functions.reduce(compose); | |
} | |
function inc(a) { | |
return a + 1; | |
} | |
function double(a) { | |
return a * 2; | |
} | |
function square(a) { | |
return a * a; | |
} | |
var pipeline1 = composeAll([inc, double, square]); | |
var pipeline2 = composeAll([double, inc, square]); | |
pipeline1(2); // => square(double(inc(2))) === 36 | |
pipeline2(2); // => square(inc(double(2))) === 25 | |
function branch(predicate, ifTrue, ifFalse) { | |
return function(data) { | |
return predicate(data) ? ifTrue(data) : ifFalse(data) | |
} | |
} | |
function greaterThan(x) { | |
return function(y) { | |
return y > x; | |
} | |
} | |
var pipeline3 = composeAll([inc, branch(greaterThan(3), double, square)]); | |
var pipeline4 = composeAll([double, branch(greaterThan(3), inc, square)]); | |
pipeline3(2); // => square(inc(2)) === 9 | |
pipeline4(2); // => inc(double(2)) === 5 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment