Last active
December 20, 2021 15:04
-
-
Save leandro/c654f3e4f25045bcd9ba5b01e08919bb to your computer and use it in GitHub Desktop.
A curry function on JS
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
const curry = (fn, arity = null) => { | |
const realArity = fn.length; | |
const providedArity = arity === null ? realArity : | |
(arity > realArity ? realArity : arity); | |
return (...args) => { | |
const argsUsed = args.length > providedArity ? providedArity : args.length; | |
const finalFn = fn.bind(this, ...args.slice(0, argsUsed)); | |
return realArity === argsUsed ? finalFn() : curry(finalFn); | |
} | |
}; | |
// Usage: | |
const testFn = (a, b, c) => [a, b, c]; | |
curry(testFn)(4); // returns a function with arity === 2 | |
curry(testFn)(4, 1); // returns a function with arity === 1 | |
curry(testFn)(4)(1); // returns a function with arity === 1 | |
curry(testFn)(4)(1)(3); // returns original function result: [4, 1, 3] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment