Created
February 13, 2015 13:51
-
-
Save stoeffel/8d230cdbaf37393cd688 to your computer and use it in GitHub Desktop.
This file contains hidden or 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 compose2(fn1, fn2) { | |
| return (...args) => fn1(fn2.apply(null, args)); | |
| } | |
| function compose(...fns) { | |
| let head = fns.shift(); | |
| let tail = fns; | |
| if (head && tail.length === 0) { | |
| return head; | |
| } | |
| if (tail.length === 1) { | |
| return compose2(head, tail[0]); | |
| } | |
| return compose2(head, compose.apply(null, tail)); | |
| } | |
| function add2(x) { | |
| return x + 2; | |
| } | |
| function sqr(x) { | |
| return x * x; | |
| } | |
| var l = console.log; | |
| l( | |
| compose(sqr)(2) | |
| ); | |
| l( | |
| compose(sqr, add2)(2) | |
| ); | |
| l( | |
| compose(sqr, add2, add2)(2) | |
| ); | |
| l( | |
| compose(sqr, add2, add2, add2)(2) | |
| ); | |
| l( | |
| compose(sqr, add2, add2, add2, add2)(2) | |
| ); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment