Skip to content

Instantly share code, notes, and snippets.

@mattijs
Created February 1, 2020 21:39
Show Gist options
  • Save mattijs/910da81da175041f3495a0ef9780c53c to your computer and use it in GitHub Desktop.
Save mattijs/910da81da175041f3495a0ef9780c53c to your computer and use it in GitHub Desktop.
Currying Module
/**
* 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