Last active
August 29, 2015 13:56
-
-
Save mattidupre/8837230 to your computer and use it in GitHub Desktop.
Combines functions into callback chain.
This file contains hidden or 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() { | |
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