Last active
December 18, 2015 13:58
-
-
Save ericnormand/5793826 to your computer and use it in GitHub Desktop.
A Javascript function for automatically creating a currying version of a function. It takes the number of arguments of the function (must be fixed) and the 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
| function autoCurry(n, f) { | |
| return function() { | |
| var args1 = Array.prototype.slice.apply(arguments), | |
| len = args1.length; | |
| if(len === n) { | |
| return f.apply(this, args1); | |
| } else if(len > n) { | |
| throw 'Too many arguments.'; | |
| } else { | |
| return autoCurry(n - len, function() { | |
| var args2 = Array.prototype.slice.apply(arguments); | |
| return f.apply(this, args1.concat(args2)); | |
| }); | |
| } | |
| } | |
| } | |
| // example | |
| function map(f, a) { | |
| var len = a.length, | |
| ret = new Array(len), | |
| i; | |
| for(i = 0; i < len; i++) { | |
| ret[i] = f(a[i]); | |
| } | |
| return ret; | |
| } | |
| var mapC = autoCurry(2, map); | |
| var incrementor = mapC(function(i){ return i + 1; }); | |
| incrementor([1,2,3]); //=> [2,3,4] | |
| function zipWith(f, a, b) { | |
| var l1 = a.length, | |
| l2 = b.length, | |
| l = l1 < l2 ? l1 : l2, | |
| ret = new Array(l), | |
| i; | |
| for(i = 0; i < l; i++) { | |
| ret[i] = f(a[i], b[i]); | |
| } | |
| return ret; | |
| } | |
| var zipWithC = autoCurry(3, zipWith); | |
| var zipAdd = zipWithC(function(i, j) {return i + j;}); | |
| var zipAddFirst3 = zipAdd([1,2,3]); | |
| zipAddFirst3([10, 100, 1000]); //=> [11, 102, 1003] | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment