JS Machine Coding Questions — Implementations You Must Know
Currying
- Transform f(a, b, c) into f(a)(b)(c) — a chain of single-argument functions.
- Key insight: Recursively return a new function until all expected arguments (fn.length) have been collected, then call the original.
- Gotcha: fn.length counts only explicitly declared parameters — rest params (...args) report 0.
- Gotcha: Partial application (passing multiple args at once) should still work.
- Gotcha: Infinite currying (no fixed arity) requires a different pattern — override valueOf/toString.
1function curry(fn) {
2 return function curried(...args) {
3 if (args.length >= fn.length) {
4 return fn.apply(this, args);
5 }
6 return function (...moreArgs) {
7 return curried.apply(this, args.concat(moreArgs));
8 };
9 };
10}
11
12function add(a, b, c) { return a + b + c; }
13const curriedAdd = curry(add);
14curriedAdd(1)(2)(3); // 6
15curriedAdd(1, 2)(3); // 6 ← partial application works too