Last active
August 29, 2015 14:09
-
-
Save dinks/73abaaac6bbac6af2344 to your computer and use it in GitHub Desktop.
Currying Javascript
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 t1(a, b, c) { | |
| console.log(a, b, c); | |
| } | |
| t1(1, 2, 3); // 1 2 3 | |
| t2 = t1.bind(undefined, 10); | |
| t2(2, 3); // 10 2 3 | |
| t3 = t2.bind(undefined, 20); // t3 = t1.bind(undefined, 10, 20); | |
| t3(3); // 10 20 3 | |
| // Generic Currying | |
| // subCurry(fn, 1)(2, 3) | |
| var subCurry = function (fn /* Multiple arguments possible */) { | |
| var args = [].slice.call(arguments, 1); // Dont take the first argument | |
| return function () { | |
| var thisArgs = Array.prototype.slice.call(arguments); | |
| return fn.apply(this, args.concat(thisArgs)); | |
| }; | |
| }; | |
| // curry(fn)(1)(2)(3) | |
| var curry = function (fn, length) { | |
| // Length will only be available after the first curry | |
| length = length || fn.length; | |
| return function () { | |
| if (arguments.length < length) { | |
| var thisArgs = Array.prototype.slice.call(arguments); | |
| var combined = [fn].concat(thisArgs); | |
| return (length - arguments.length > 0) ? | |
| curry(subCurry.apply(this, combined), length - arguments.length): | |
| subCurry.call(this, combined); | |
| } else { | |
| return fn.apply(this, arguments); | |
| } | |
| }; | |
| }; | |
| var fn = function(x, y, z) { return x+y+z; } | |
| var mFn = curry(fn); | |
| console.log(mFn(1)(2, 3)); | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment