Skip to content

Instantly share code, notes, and snippets.

@Raynos
Created June 19, 2012 19:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save Raynos/2955915 to your computer and use it in GitHub Desktop.
Save Raynos/2955915 to your computer and use it in GitHub Desktop.
Function composition
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)
}
}
}
}​
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