Skip to content

Instantly share code, notes, and snippets.

@robotlolita

robotlolita/.js Secret

Created July 22, 2016 03:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save robotlolita/ccecb9b6781ba085d142040a943e1a96 to your computer and use it in GitHub Desktop.
Save robotlolita/ccecb9b6781ba085d142040a943e1a96 to your computer and use it in GitHub Desktop.
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