Created
April 15, 2010 02:26
-
-
Save chrislewis/366614 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
/* 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