Last active
April 10, 2022 18:47
-
-
Save neftaly/b77455b3df9a8b50bf8b to your computer and use it in GitHub Desktop.
ES6 Auto-curry
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
| const curry = (fn, preArgs = []) => (...postArgs) => { | |
| const args = [...preArgs, ...postArgs]; // Combine old and new arguments | |
| if (args.length < fn.length) { // Check ig enough arguments received | |
| return curry(fn, args); // Recurse to emit an argument receiver fn | |
| } | |
| return fn(...args); // Finished; Apply arguments to fn and return result | |
| }; |
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
| const add3 = function (a, b, c) { | |
| return a + b + c; | |
| }; | |
| const x = curry(add3); | |
| x(1)(1)(1); //=> 3 | |
| x(1, 1)(1); //=> 3 | |
| x(1, 1, 1); //=> 3 |
Author
Looks good! This was actually for explaining how auto-currying worked in a talk, so I wouldn't have used bind (too much cognitive load for audience), but it'd be great otherwise.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I like what you have here.
I think you can reduce this to:
Please let me know your thoughts or if there is some functionality lost.