Skip to content

Instantly share code, notes, and snippets.

@leandro
Last active December 20, 2021 15:04
Show Gist options
  • Save leandro/c654f3e4f25045bcd9ba5b01e08919bb to your computer and use it in GitHub Desktop.
Save leandro/c654f3e4f25045bcd9ba5b01e08919bb to your computer and use it in GitHub Desktop.
A curry function on JS
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