Last active
August 15, 2017 11:04
-
-
Save torgeir/85532dcac47710d5be66 to your computer and use it in GitHub Desktop.
JavaScript curry function that can handle partial application of any level when the function is applied.
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
curry = function (fn) { | |
var numargs = fn.length; | |
return createRecurser([]); | |
function createRecurser (acc) { | |
return function () { | |
var args = [].slice.call(arguments); | |
return recurse(acc, args); | |
}; | |
} | |
function recurse (acc, args) { | |
var newacc = acc.concat(args); | |
if (newacc.length < numargs) { | |
return createRecurser(newacc); | |
} | |
else { | |
return fn.apply(this, newacc); | |
} | |
} | |
} | |
var add = curry(function (a, b, c) { | |
return a + b + c; | |
}); | |
var add2 = add(2); | |
var add4 = add2(2); | |
console.log(add(2)(2)(2)); // 6 | |
console.log(add2(2)(3)); // 7 | |
console.log(add2(2)(4)); // 8 | |
console.log(add4(5)); // 9 | |
var times = curry(function (a, b, c) { | |
return a * b * c; | |
}); | |
var times2 = times(2); | |
var times4 = times2(2); | |
console.log(times(2)(2)(2)); // 8 | |
console.log(times2(2)(3)); // 12 | |
console.log(times4(4)); // 16 | |
console.log(times(2, 3, 4)); // 24 | |
console.log(times(2)(3, 4)); // 24 | |
console.log(times(2, 3)(4)); // 24 | |
console.log(times(2)(3)(4)); // 24 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
And a sweet.js autocurry macro http://bit.ly/js-autocurry