Last active
November 4, 2017 19:58
-
-
Save Tahseenm/a166fb5154c45840eeefd214b6ceff01 to your computer and use it in GitHub Desktop.
Curry a function
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
/** (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