Skip to content

Instantly share code, notes, and snippets.

@tuscen
Last active October 16, 2015 07:23
Show Gist options
  • Save tuscen/edb0cac2aaaabe44a68f to your computer and use it in GitHub Desktop.
Save tuscen/edb0cac2aaaabe44a68f to your computer and use it in GitHub Desktop.
Function.prototype.curry = function(...args) {
let fn = this;
let f = (...restArgs) => {
if (fn.length < args.length + restArgs.length) {
args = args.concat(restArgs);
return fn.apply(this, args.slice(0, fn.length));
} else {
args = args.concat(restArgs);
return f;
}
};
return f;
};
// -----------------------------------
// Example
// -----------------------------------
let foo = function(a, b, c, d, e, f) {
return Array.prototype.slice.call(arguments).reduce((acc, el) => acc + el,0);
}
let curriedFoo = foo.curry(1, 2, 3, 4, 5, 6);
console.log(curriedFoo());
curriedFoo = foo.curry(1, 2);
console.log(curriedFoo(3, 4)(5, 6));
// ---------------------------------
function curry(fn, ...args) {
let f = (...restArgs) => {
if (fn.length < args.length + restArgs.length) {
args = args.concat(restArgs);
return fn.apply(undefined, args.slice(0, fn.length));
} else {
args = args.concat(restArgs);
return f;
}
};
return f;
};
// -----------------------------------
// Example
// -----------------------------------
let foo = function(a, b, c, d, e, f) {
return Array.prototype.slice.call(arguments).reduce((acc, el) => acc + el,0);
}
let curriedFoo = curry(foo, 1, 2, 3, 4, 5, 6);
console.log(curriedFoo());
curriedFoo = curry(foo, 1, 2);
console.log(curriedFoo(3, 4, 5)(6));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment