🟑 MediumFunctionsπŸ“– Theory Question

What is currying and how do you implement a generic curry function?

πŸ’‘

Hint

Transform f(a,b,c) into f(a)(b)(c) β€” each call returns a new function waiting for more args

Full Answer

Currying transforms a multi-argument function into a chain of unary functions, each waiting for one argument at a time.

// Manual curried function
const add = a => b => c => a + b + c;
add(1)(2)(3); // 6
const add1 = add(1);     // partially applied β€” waits for b and c
const add1and2 = add1(2); // waits for c
add1and2(3);              // 6

// Generic curry utility
function curry(fn) {
  return function curried(...args) {
    if (args.length >= fn.length) { // enough args collected?
      return fn(...args);
    }
    return (...moreArgs) => curried(...args, ...moreArgs);
  };
}

const sum = (a, b, c) => a + b + c;
const curriedSum = curry(sum);
curriedSum(1)(2)(3); // 6
curriedSum(1, 2)(3); // 6 β€” also works (partial application hybrid)

Currying enables: partial application, point-free style, composable specialized functions.

πŸ’‘ Currying vs Partial Application: currying always breaks a function into unary steps. Partial application pre-fills SOME arguments and returns a function waiting for the rest.

More Functions Questions

🟒 EasyWhat is the difference between call, apply, and bind?β†’πŸŸ’ EasyHow do arrow functions differ from regular functions?β†’πŸŸ’ EasyWhat is a pure function and why does it matter?β†’πŸŸ’ EasyWhat are Higher-Order Functions (HOF)?β†’

Practice this in a timed sprint β†’

5 free questions, no signup required

⚑ Start Sprint