Skip to content

Instantly share code, notes, and snippets.

@puiutucutu
Last active September 19, 2019 17:49
Show Gist options
  • Save puiutucutu/21c4b188eb175bb0a1a2f07563e4846c to your computer and use it in GitHub Desktop.
Save puiutucutu/21c4b188eb175bb0a1a2f07563e4846c to your computer and use it in GitHub Desktop.
curry
const isEveryArgumentProvided = x => y => x >= y;
function curry(f)
{
function curried(...initialArgs) {
if (initialArgs.length > f.length) {
throw new Error(
`Function \`${f.name}\` supplied ${initialArgs.length} args when expecting ${f.length} args`
);
}
return isEveryArgumentProvided (initialArgs.length) (f.length)
? f.apply(this, initialArgs) // received all args for f
: (...remainingArgs) => curried.apply(this, [...initialArgs, ...remainingArgs]) // more args needed for f
;
}
return curried;
}
const adder = (x, y) => x + y;
const curriedAdder = curry(adder);
curriedAdder (1) (2) (3); //=> Error: curriedAdder(...)(...) is not a function
curriedAdder (1, 2, 3); //=> Error: Function `adder` supplied 3 args when expecting 2 args
function curry(f)
{
function curried(...args) {
return args.length >= f.length
? f.apply(this, args)
: (...remainingArgs) => curried.apply(this, [...args, ...remainingArgs])
;
}
return curried;
}
const adder = (x, y) => x + y;
const curriedAdder = curry (adder);
const a = curriedAdder (1) (2); //=> 3
const b = curriedAdder (1, 2); //=> 3
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment