Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
curryAndCall as a prototype method for Functions
Function.prototype.curryAndCall = function () {
var args = Array.prototype.slice.call(arguments);
var curry = function (originalFunc, collectedArgs) {
return function () {
var args = Array.prototype.slice.call(arguments);
if (args.length + collectedArgs.length >= originalFunc.length) {
return originalFunc.apply(originalFunc, collectedArgs.concat(args));
} else {
return curry(originalFunc, collectedArgs.concat(args));
}
}
};
if (args.length >= this.length) {
return this.apply(this, args);
} else {
return curry(this, args);
}
};
// Test subject: function with 4 arguments.
var logFour = function (a, b, c, d) {
console.log('--------->', a, b, c, d);
};
// Keep pre-populating arguments for logFour() until we have all four,
// then call the original function with all collected arguments.
logFour.curryAndCall(1)(2,3)(4);
@timotgl
Copy link
Author

timotgl commented Mar 7, 2016

Inspired by https://gist.github.com/alexdiliberto/2a516eeea9a4d9eb52e2 but I tried to avoid using additional helper functions.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment