Skip to content

Instantly share code, notes, and snippets.

@mattidupre
Last active August 29, 2015 13:56
Show Gist options
  • Save mattidupre/8837230 to your computer and use it in GitHub Desktop.
Save mattidupre/8837230 to your computer and use it in GitHub Desktop.
Combines functions into callback chain.
function compose() {
function c(fn, next) {
return function() {
var args = Array.prototype.slice.call(arguments, 0);
fn.apply(fn, [next].concat(args));
}
}
var fn = arguments[arguments.length-1];
for (var f=arguments.length-2; f>=0; f--) {
fn = c(arguments[f], fn);
}
return fn;
}
// demo
var x = function(next, a, b, c) {
a++;
c--;
next(a, b, c);
}
var y = function(next, d, e, f) {
d = '('+d+')';
e = '('+e+')';
f = '('+f+')';
next(d, e, f);
}
var z = function(g, h, i) {
alert(g+','+h+','+i);
}
var demo = compose(x, y, z);
demo(1, 2, 3); // alerts (2),(2),(2)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment