Skip to content

Instantly share code, notes, and snippets.

@samarpanda
Created March 27, 2015 06:56
Show Gist options
  • Save samarpanda/168e4264487fc50db085 to your computer and use it in GitHub Desktop.
Save samarpanda/168e4264487fc50db085 to your computer and use it in GitHub Desktop.
AutoCurry snippet
/**
* To Array
*/
function toArray(args) {
return [].slice.call(args);
}
/**
* Curry function
*/
function curry(fn){
var args = Array.prototype.slice.call(arguments, 1);
function f(){
return fn.apply(this, args.concat(toArray(arguments)));
}
return f;
}
/**
* Auto Curry function
*/
function autoCurry(fn, numArgs) {
numArgs = numArgs || fn.length;
function f() {
if (arguments.length < numArgs)
{
return numArgs - arguments.length > 0 ?
autoCurry(curry.apply(this, [fn].concat(toArray(arguments))),
numArgs - arguments.length) :
curry.apply(this, [fn].concat(toArray(arguments)));
}
else
{
return fn.apply(this, arguments);
}
}
f.toString = function() { return fn.toString(); };
f.curried = true;
return f;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment