Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save torgeir/85532dcac47710d5be66 to your computer and use it in GitHub Desktop.
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.
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
@follesoe
Copy link

follesoe commented Jul 8, 2014

Next: Rupi-macro

@torgeir
Copy link
Author

torgeir commented Jul 14, 2014

And a sweet.js autocurry macro http://bit.ly/js-autocurry

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment