Skip to content

Instantly share code, notes, and snippets.

@umcconnell
Created May 26, 2019 16:52
Show Gist options
  • Save umcconnell/ca9dd33b00839f520b1ad9159e990e1e to your computer and use it in GitHub Desktop.
Save umcconnell/ca9dd33b00839f520b1ad9159e990e1e to your computer and use it in GitHub Desktop.
Curry a JS function
/**
* Takes a function and curries it
* @param {function} func input non-curried function
* @param {number} [amountArgs=func.length] number of arguments to collect; defaults to func.length
* @example
* let plus = (a, b) => a+b;
* let curriedPlus = curry(plus);
* curriedPlus(1)(2)
* // => 3
* @returns a collect function for collecting the arguments and calling the input function
*/
let curry = (func, amountArgs = func.length) => {
let collected = new Array();
return function collect(...args) {
collected.push(...args);
if (collected.length >= amountArgs) {
let tempCollected = collected;
collected = new Array();
return func(...tempCollected);
}
return collect;
};
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment