Last active
September 19, 2019 17:49
-
-
Save puiutucutu/21c4b188eb175bb0a1a2f07563e4846c to your computer and use it in GitHub Desktop.
curry
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 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 |
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
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