Functional patterns · core
Currying, partial application and infinite currying
Currying turns f(a, b, c) into f(a)(b)(c) by returning a closure that collects arguments until it has fn.length of them, while infinite currying like sum(1)(2)(3)() keeps returning a function that holds the running total until an empty call (or a conversion to a primitive) ends it.
Explain it out loud
Explain it out loud to an AI interviewer that follows up, and see where your answer is thin.
Practise by voiceThe notes
What you must know
- curry(fn): if the collected arguments >= fn.length, call fn; otherwise return a function that collects more. Support several arguments per call: add(1, 2)(3).
- fn.length ignores default and rest parameters, so curry needs an explicit arity for such functions.
- Partial application fixes some arguments now (with bind or a closure); currying is one form of it.
- Infinite sum: sum(a) returns b => (b === undefined ? a : sum(a + b)).
- Without a terminating call, give the returned function a Symbol.toPrimitive (or valueOf) that returns the total, so sum(1)(2) + 0 is 3. console.log still prints the function itself.
- Follow-ups: placeholders (lodash's _), and real uses such as configurable selectors, event handlers with ids and logger(level)(message).
The red pen
Common traps: mistake → fix
Mistake: Hard-coding three levels
Fix: it must work for any length.
Mistake: Forgetting several arguments per call or this.
Mistake: console.log(sum(1)(2)) prints 3 with toPrimitive
Fix: it prints the function; conversion happens only with +, templates or ==.
Easy to hard
Questions interviewers ask, easy to hard
- What is currying? How is it different from partial application?
- Implement curry(fn) that supports add(1)(2)(3) and add(1, 2)(3).
- Make sum(1)(2)(3)() work for any number of calls. (Zepto, Flipkart)
- Make sum(1)(2)(3) work with no terminating call.
- Add placeholder support. Why do default parameters break fn.length?
Explain it out loud
Explain it out loud to an AI interviewer that follows up, and see where your answer is thin.
Practise by voiceYour first interview is free
Sign up and start with a 15-minute interview with the full report, and an English conversation. No card needed.