Skip to content

Instantly share code, notes, and snippets.

@fedesilva
Forked from chrislewis/gist:366614
Created April 15, 2010 13:43
Show Gist options
  • Save fedesilva/367100 to your computer and use it in GitHub Desktop.
Save fedesilva/367100 to your computer and use it in GitHub Desktop.
/* Recursively compose an arbitrarily long list of functions into a single function. */
function compose() {
/* One function, nothing to compose. */
if(arguments.length == 1)
return arguments[0];
else {
/* Compose the head with the immediate successor. */
var args = arguments;
/* The composition: f(g(x)) */
var f = [function() {
return args[1].apply(null, [args[0].apply(null, arguments)]);
}];
/* If we haven't composed all, use the new composition as the head for the next. */
return compose.apply(null, arguments.length == 2
? f : f.concat(Array.prototype.slice.apply(arguments, [2])));
}
}
/* Examples */
var composed = compose(
function(i) {
return "is " + i;
},
function(j) {
return "name " + j;
},
function(i) {
return "my " + i;
}
)
alert(composed("Chris"));
/* Yields "my name is Chris" */
/* Call stack: ("my " + ("name " + ("is " + ("Chris")))) */
composed = compose(
function(i) {
return i * 4;
},
function(j) {
return j / 2;
},
function(i) {
return i + 1;
}
)
alert(composed(1));
/* Yields 3 */
/* Call stack: ((((1) * 4) / 2) + 1) */
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment