Skip to content

Instantly share code, notes, and snippets.

@timotgl
Created March 7, 2016 18:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save timotgl/8eba8203ba1746bf727e to your computer and use it in GitHub Desktop.
Save timotgl/8eba8203ba1746bf727e to your computer and use it in GitHub Desktop.
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