Skip to content

Instantly share code, notes, and snippets.

@txus
Last active December 20, 2015 05:19
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save txus/6077658 to your computer and use it in GitHub Desktop.
Save txus/6077658 to your computer and use it in GitHub Desktop.
Function Composition in Javascript
comp = (fns...) ->
(arg) ->
fns.reverse().reduce((x, fn) ->
fn(x)
, arg)
timesthree = (a) -> a * 3
timestwo = (a) -> a * 2
negative = (a) -> -a
composed = comp(timesthree, timestwo, negative)
console.log composed(10)
function comp() {
var fns = [].slice.apply(arguments);
return function(arg) {
return fns.reverse().reduce(function(x, fn) { return fn(x); }, arg);
};
}
function timesthree(a) {
return a * 3;
}
function timestwo(a) {
return a * 2;
}
function negative(a) {
return -a;
}
var composed = comp(timesthree, timestwo, negative);
console.log(composed(10)) // -60
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment