Last active
April 28, 2020 03:24
-
-
Save rtm/96ca45ee4b30df36e40b to your computer and use it in GitHub Desktop.
Currify a function
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
// Transform a function into one which takes partial arguments, | |
// returning a function which can be invoked with the remaining ones. | |
function currify(f) { | |
var len = f.length; | |
return function _f() { | |
var old_args = arguments; | |
return function() { | |
var args = []; | |
for (let i = 0, l = old_args.length; i < l; i++) args[args.length] = old_args[i]; | |
for (let i = 0, l = arguments.length; i < l; i++) args[args.length] = arguments[i]; | |
return (args.length >= len ? f : _f).apply(this, args); | |
}; | |
}(); | |
} | |
//function add(a, b, c) { return a + b + c; } | |
//var _add = currify(add); | |
//console.log(_add(1)(2)(3)); | |
//console.log(_add(1, 2)(3)); | |
//console.log(_add(1)(2, 3)); | |
//console.log(_add(1, 2, 3)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I found that curry can be done with lesser nested functions,
the logic and syntax is simpler and comprehensible (thanks to ES6 :D)
https://gist.github.com/AoiYamada/ae494f6b710f5bd70018a70828c083d8