Created
May 26, 2019 16:52
-
-
Save umcconnell/ca9dd33b00839f520b1ad9159e990e1e to your computer and use it in GitHub Desktop.
Curry a JS 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
/** | |
* 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