Currying & Partial Application in JavaScript
JS جاوااسکریپت

Currying & Partial Application in JavaScript

Transform multi-argument functions into reusable pipelines — a favorite functional programming interview topic.

BugCast Admin··۵ دقیقه مطالعه

Currying and partial application both fix some arguments ahead of time, but they serve slightly different goals. Interviews often ask you to implement one or use them in event handlers and API clients.

Common Interview Questions

Q: What is currying?

Answer: Currying transforms a function f(a, b, c) into a chain f(a)(b)(c) where each call returns a new function until all arguments are supplied.


const add = (a) => (b) => (c) => a + b + c;
add(1)(2)(3); // 6

Q: How is partial application different?

Answer: Partial application fixes some arguments now and returns a function expecting the rest: const add5 = (x) => add(5, x). You do not need one-argument-at-a-time nesting.


function partial(fn, ...fixed) {
  return (...rest) => fn(...fixed, ...rest);
}

Q: When is currying useful in real code?

Answer: Configuration pipelines, reusable validators, middleware-style composition, and libraries like Ramda. It shines when you create specialized functions from general ones.

Q: Implement a simple curry helper

Answer: Collect arguments until the count matches fn.length, then invoke. Note: rest parameters and default params can make fn.length unreliable in edge cases.


function curry(fn) {
  return function curried(...args) {
    if (args.length >= fn.length) return fn(...args);
    return (...more) => curried(...args, ...more);
  };
}

Key Points for Interviews

  • Currying: one argument per function call

  • Partial application: fix a batch of arguments once

  • Both enable function composition and DRY configuration

  • Arrow functions and closures make implementation straightforward

  • Over-currying hurts readability — use when it adds clarity

#currying#functional#interview

مطالب مرتبط