Curry a function
A JavaScript exercise from Scriptdrill. Solve it with a code editor in your browser that runs your function against example and hidden tests, and it is checked the moment you submit.
The task
`fn` takes a fixed number of parameters, available as `fn.length`. Return a curried version: it accepts the arguments in any grouping, `c(1)(2)(3)`, `c(1, 2)(3)` or `c(1, 2, 3)`, and calls `fn` once it has received at least `fn.length` arguments, returning `fn`'s result. Extra arguments are passed along. A function with 0 or 1 parameters runs on the first call. Partial applications are independent and reusable: with `const add1 = c(1)`, both `add1(2)` and `add1(3)` work and give 3 and 4.
What this exercise teaches
Each partial application closes over its own copy of the arguments so far, so reusing one never leaks arguments into another. Comparing with >= rather than === is what lets extra arguments through instead of returning yet another function.
A hint if you get stuck
Write an inner `curried(...args)`: if `args.length >= fn.length` return `fn(...args)`; otherwise return `(...more) => curried(...args, ...more)`. Spreading into a new array each time is what keeps partial applications independent.
Try it now, free, no account needed
Every exercise on Scriptdrill is free to try. Open it on the practice page, solve it, and get instant feedback with a hint. The worked solution opens once you solve it or after two tries.
Open this exerciseMore exercises in Async and functions
- A counter with private stateFree
- Sleep with a PromiseFree
- Retry a failing callFree
- Promise.all with a concurrency limitFree
- DebounceFree
- MemoizeFree
- Run only onceFree
- Pipe functions togetherFree
- Timeout wrapperFree
- Run tasks in sequenceFree
- ThrottleFree
- Event emitterFree
- LRU cacheFree
- Write your own Promise.allFree
- Callback style to a PromiseFree