Skip to content

Instantly share code, notes, and snippets.

@FireyFly
Created July 11, 2012 23:54
Show Gist options
  • Save FireyFly/3094544 to your computer and use it in GitHub Desktop.
Save FireyFly/3094544 to your computer and use it in GitHub Desktop.
//-- Definition
Function.prototype.compose = function (/* ...args */) {
var args = Array.prototype.slice.call(arguments)
, funs = [ this ].concat(args)
return function (/* ... */) {
return funs.reduceRight(function (args, f) {
return [ f.apply(null, args) ]
}, arguments)[0]
}
}
//-- Usage
var add10 = function(x) { return x + 10 }
, mul2 = function(x) { return x * 2 }
, add4 = function(x) { return x + 4 }
var composed = add10.compose(mul2, add4)
console.log(composed(5))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment