Created
June 13, 2014 08:57
-
-
Save Williammer/9d7342d749ba733cb47b to your computer and use it in GitHub Desktop.
jsPattern.currySchonfinkelize.js - one general purpose curry function to partially exec arguments to the fn argument.
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 schonfinkelize(fn) { | |
| var slice = Array.prototype.slice, | |
| stored_args = slice.call(arguments, 1); | |
| return function () { | |
| var new_args = slice.call(arguments), | |
| args = stored_args.concat(new_args); | |
| return fn.apply(null, args); | |
| }; | |
| } | |
| //test | |
| // a normal function | |
| function add(x, y) { | |
| return x + y; | |
| } | |
| // curry a function to get a new function | |
| var newadd = schonfinkelize(add, 5); | |
| newadd(4); // 9 | |
| // another option -- call the new function directly | |
| schonfinkelize(add, 6)(7); // 13 | |
| // a normal function | |
| function add(a, b, c, d, e) { | |
| return a + b + c + d + e; | |
| } | |
| // works with any number of arguments | |
| schonfinkelize(add, 1, 2, 3)(5, 5); // 16 | |
| // two-step currying | |
| var addOne = schonfinkelize(add, 1); | |
| addOne(10, 10, 10, 10); // 41 | |
| var addSix = schonfinkelize(addOne, 2, 3); | |
| addSix(5, 5); // 16 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment