Last active
December 20, 2015 05:19
-
-
Save txus/6077658 to your computer and use it in GitHub Desktop.
Function Composition in Javascript
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
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) |
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
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