Created
May 4, 2014 15:48
-
-
Save alexdiliberto/2a516eeea9a4d9eb52e2 to your computer and use it in GitHub Desktop.
Curry functions in Javascript with variable argument lengths
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 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