Curry
JS Functions
Medium
20 min
closures
functional programming
currying
Implement curry(func). It returns a curried version of func that collects arguments over any number of calls. As soon as it has collected at least func.length arguments, it calls func with all of them and returns the result. Until then, each call returns another function that waits for more.
function volume(length, width, height) {
return length * width * height;
}
const curried = curry(volume);
curried(2, 3, 4); // 24
curried(2)(3)(4); // 24
curried(2, 3)(4); // 24
curried(2)(3, 4); // 24
const base = curried(2);
base(3)(4); // 24
base(5)(1); // 10 (base is reusable; calls don't affect each other)
Requirements
- The arity is
func.length(the number of declared parameters before the first default or rest parameter). - Each call may pass any number of arguments, including zero. A call with no arguments returns a function that still waits for the same arguments.
- When the total number of collected arguments reaches the arity, call
funcwith all collected arguments, including any extras beyond the arity. - Partially applied functions are reusable: calling one twice with different arguments must give independent results.
thisfrom the final call is forwarded tofunc, so a curried function can be used as a method.- If
func.lengthis0, calling the curried function invokesfuncimmediately.
Follow-up
func.lengthis0for(...args) => {}and1for(a, b = 2) => {}. How would you let callers pass an explicit arity?- Where does currying actually help in front-end code, and where does it hurt readability?
- How would you support placeholders (see Curry II)?
Spotted a mistake or a rights concern? Report an issue