Last active
April 26, 2021 00:51
-
-
Save chasm/f3ead2de4ea1dcda795642fa74411911 to your computer and use it in GitHub Desktop.
Function to curry other functions
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 curryN(f, n) { | |
return (...args) => { | |
return args.length < n | |
? (...rest) => curryN(f, n)(...args, ...rest) | |
: f(...args) | |
} | |
} | |
function curry(f) { | |
const numberOfParams = f.length | |
return curryN(f, numberOfParams) | |
} | |
const curriedAdd = curry((a, b, c) => a + b + c) | |
curriedAdd() // returns curry((a, b, c) => a + b + c) | |
curriedAdd(3) // returns curry((b, c) => 3 + b + c) | |
curriedAdd(3)(4) // returns curry((c) => 3 + 4 + c) | |
curriedAdd(3)(4)(5) // returns 12 | |
curriedAdd(3, 4)(5) // returns 12 | |
curriedAdd(3)(4, 5) // returns 12 | |
curriedAdd(3, 4, 5) // returns 12 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment