Curry
Implement curry(fn). The curried function collects arguments over one or more calls and runs fn when it has at least fn.length of them. A call may pass several arguments. Each partial call returns a new function and must not change an earlier one, so a partial can be reused. In the tests fn joins its arguments with a dash.
Start from
function curry(fn) {
// Return a function that collects arguments until fn can run.
}Hints
Each hint gives away a little more. Open one only when you need it.
Hint 1
Compare the number of collected arguments with fn.length.
Hint 2
When there are not enough, return a new function that calls the curried one again with the old and the new arguments together.
Solution
From here on the page gives the method away. If you are still solving, go back to the hints.
JavaScript
function curry(fn) {
return function curried(...args) {
if (args.length >= fn.length) return fn.apply(this, args);
return (...more) => curried.apply(this, [...args, ...more]);
};
}What an interviewer looks for
It tests recursion over closures and fn.length. The follow-up is usually partial application, and where currying helps in real code.