28Implement curry() supporting partial application
mediumAbout 35 minutesCodingclosuresfunctional-programming
Problem
Implement curry(fn). It returns a curried version of fn that keeps collecting arguments until it has at least fn.length of them, then calls fn with all of them. Arguments can arrive one at a time or several at once.
const volume = curry((l, w, h) => l * w * h);
volume(2)(3)(4); // 24
volume(2, 3)(4); // 24
volume(2)(3, 4); // 24
volume(2, 3, 4); // 24
const area = volume(2);
area(3)(4); // 24, and area can be reused
area(5)(1); // 10Requirements
- Every partial application returns a new function and can be reused independently.
- Extra arguments beyond
fn.lengthare passed through tofn. - Calling with no arguments before enough are collected returns a curried function, it does not call
fn. - Keep the
thisvalue the final call was made with.
Try it yourself
Write your solution, run it, then submit to check it against the tests.
solution.jsJavaScript
Press Run or ⌘ Enter to execute your code.
Video walkthroughs
Stuck? Watch someone solve it, then try again on your own.
Step-by-step
A function's length is the number of parameters it declares (before any default value or rest parameter). That is how many arguments the curried function needs to collect.
Unlock the full solution
What's inside
- Step-by-step
- Approach
- Solution
- Complexity
- Edge cases
- Follow-up questions
- Tests
Includes 2 code listings, 5 edge cases, 4 follow-up questions.
One-time payment by UPI, card or net banking. Launch price.