Skip to content

Instantly share code, notes, and snippets.

@Tahseenm
Last active November 4, 2017 19:58
Show Gist options
  • Save Tahseenm/a166fb5154c45840eeefd214b6ceff01 to your computer and use it in GitHub Desktop.
Save Tahseenm/a166fb5154c45840eeefd214b6ceff01 to your computer and use it in GitHub Desktop.
Curry a function
/** (fn: Function) -> Function **/
const curry = (fn) => {
/** (fn: Function, totalArgs: number) -> Function **/
const curryFunc = (fn, totalArgs) => {
const curriedFunc = (...args) => {
if (args.length === 0) {
throw new Error('Please provide the required arguments')
}
if (totalArgs === args.length) return fn(...args)
const remainingArgs = totalArgs - args.length
return curryFunc((...rest) => fn(...args, ...rest), remainingArgs)
}
return curriedFunc
}
return curryFunc(fn, fn.length)
}
/**
* Example
*/
const add = curry((a, b) => a + b)
const volume = curry((l, w, h) => l * w * h)
console.log(add(2, 2))
console.log(add(2)(2))
console.log(volume(1, 2, 3))
console.log(volume(1)(2, 3))
console.log(volume(1)(2)(3))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment