Created
March 27, 2015 06:56
-
-
Save samarpanda/168e4264487fc50db085 to your computer and use it in GitHub Desktop.
AutoCurry snippet
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
/** | |
* 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