Created
June 19, 2012 19:02
-
-
Save Raynos/2955915 to your computer and use it in GitHub Desktop.
Function composition
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
var slice = [].slice | |
function compose() { | |
var context = {} | |
return slice.call(arguments).reduceRight(combineFunctions) | |
function combineFunctions(memo, current) { | |
return applyInOrder | |
function applyInOrder() { | |
var result = current.apply(context, arguments) | |
return memo.call(context, result) | |
} | |
} | |
} | |
function composeAsync() { | |
var context = {} | |
return slice.call(arguments).reduce(combineFunctions) | |
function combineFunctions(memo, outer) { | |
return applyInOrder | |
function applyInOrder() { | |
var inner = arguments[arguments.length - 1], | |
arguments[arguments.length - 1] = applyOuter | |
memo.apply(context, arguments) | |
function applyOuter() { | |
var args = [].slice.call(arguments).concat(inner) | |
outer.apply(context, args) | |
} | |
} | |
} | |
} |
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
var composedAsync = composeAsync( | |
function(a, cb) { return cb(a * 2) }, | |
function(b, cb) { return cb(b * 3) }, | |
function(c, cb) { return cb(c * 4) } | |
) | |
composedAsync(4, console.log) | |
var composed = compose( | |
function(a) { return a * 2 }, | |
function(b) { return b * 3 }, | |
function(c) { return c * 4 } | |
) | |
console.log(composed(4)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment