Skip to content

Instantly share code, notes, and snippets.

@alexdiliberto
Created May 4, 2014 15:48
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save alexdiliberto/2a516eeea9a4d9eb52e2 to your computer and use it in GitHub Desktop.
Save alexdiliberto/2a516eeea9a4d9eb52e2 to your computer and use it in GitHub Desktop.
Curry functions in Javascript with variable argument lengths
function toArray(args) {
return [].slice.call(args);
}
function sub_curry(fn /*, variable number of args */) {
var args = [].slice.call(arguments, 1);
return function () {
return fn.apply(this, args.concat(toArray(arguments)));
};
}
function curry(fn, length) {
// capture fn's # of parameters
length = length || fn.length;
return function () {
if (arguments.length < length) {
// not all arguments have been specified. Curry once more.
var combined = [fn].concat(toArray(arguments));
return length - arguments.length > 0
? curry(sub_curry.apply(this, combined), length - arguments.length)
: sub_curry.call(this, combined );
} else {
// all arguments have been specified, actually call function
return fn.apply(this, arguments);
}
};
}
var fn = curry(function(a, b, c) { return [a, b, c]; });
// these are all equivalent
fn("a", "b", "c");
fn("a", "b")("c");
fn("a")("b", "c");
fn("a")("b")("c");
//=> ["a", "b", "c"]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment