Created
June 27, 2014 22:24
-
-
Save Integralist/ffe7f134a2ed1ecb62c7 to your computer and use it in GitHub Desktop.
Auto Currying JavaScript Function
This file contains 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
// Copied from http://javascriptweblog.wordpress.com/2010/06/14/dipping-into-wu-js-autocurry/ | |
var autoCurry = (function () { | |
var toArray = function toArray(arr, from) { | |
return Array.prototype.slice.call(arr, from || 0); | |
}, | |
curry = function curry(fn /* variadic number of args */) { | |
var args = toArray(arguments, 1); | |
return function curried() { | |
return fn.apply(this, args.concat(toArray(arguments))); | |
}; | |
}; | |
return function autoCurry(fn, numArgs) { | |
numArgs = numArgs || fn.length; | |
return function autoCurried() { | |
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); | |
} | |
}; | |
}; | |
}()); | |
marks = autoCurry(name)('Mark'); | |
bobs = marks('Bob Smith'); | |
bobs('McDonnell'); // => "Mark Bob Smith McDonnell" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment