Last active
September 7, 2021 21:39
-
-
Save mkuklis/5294248 to your computer and use it in GitHub Desktop.
auto curry 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
function toArray(args) { | |
return [].slice.call(args); | |
} | |
function autocurry(fn) { | |
var len = fn.length; | |
var args = []; | |
return function next() { | |
args = args.concat(toArray(arguments)); | |
return (args.length >= len) ? | |
fn.apply(this, args.splice(0)) : | |
next; | |
} | |
} | |
// usage | |
var add = autocurry(function (a, b, c, d) { | |
return a + b + c + d; | |
}); | |
add(1)(2)(3)(4); // 10 | |
var one = add(1); | |
one(4, 5, 6); // 16 | |
add(2)(3, 4)(5); // 14 | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Fixed curry function that does not store state in scope between multiple calls (also typed for up-to 2 arguments):