Created
February 1, 2020 21:39
-
-
Save mattijs/910da81da175041f3495a0ef9780c53c to your computer and use it in GitHub Desktop.
Currying Module
This file contains hidden or 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
/** | |
* Curry the given function. | |
* | |
* @param {Function} fn | |
* @param {[...*]} initialArgs | |
* @returns {Function|*} | |
*/ | |
export function curry(fn, ...initialArgs) { | |
return curryN(fn.length, fn, ...initialArgs); | |
} | |
/** | |
* Curry the given function up until the specified arity. | |
* | |
* @param {number} arity | |
* @param {Function} fn | |
* @param {[...*]} initialArgs | |
* @returns {Function|*} | |
*/ | |
export function curryN(arity, fn, ...initialArgs) { | |
if (arity === 0) return fn; | |
return function curried(...args) { | |
const combinedArgs = initialArgs.concat(args); | |
return (combinedArgs.length >= arity) | |
? fn(...combinedArgs) | |
: curryN(arity, fn, ...combinedArgs); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment