Last active
April 21, 2017 01:05
-
-
Save paultopia/79ef381b261e4d07401db32cb1323ade to your computer and use it in GitHub Desktop.
Implementing basic functional idioms in JS---partial application, composition. Because I hate "bind." No, actually, just as a learning exercise, trying to get more familiar with JS quirks.
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 partial(func, arg){ | |
| return function(){ | |
| var args = arguments ? [].slice.call(arguments) : [] | |
| args.unshift(arg); | |
| return func.apply(null, args); | |
| }; | |
| } | |
| // comp applies functions right to left, like Clojure. | |
| function comp(func1, func2){ | |
| return function(){ | |
| var args = arguments ? [].slice.call(arguments) : null | |
| return func1(func2.apply(null, args)); | |
| }; | |
| } | |
| // example of using partial application: | |
| function add(x, y){return x + y;} | |
| var add5 = partial(add, 5); | |
| console.log(add5(10)); // prints 15 | |
| // example of using composition: | |
| function times3(x){return x * 3;} | |
| var t3p5 = comp(add5, times3); | |
| console.log(t3p5(1)); // prints 8 | |
| var p5t3 = comp(times3, add5); | |
| console.log(p5t3(1)); // prints 18 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment