Course contentsShow
← JavaScript
Lesson 1767 of 2,72337. Functional Programming PatternsFree lesson

Writing a Generic Curry Helper

Build a reusable curry function that transforms any multi-argument function automatically.

Writing a Generic Curry Helper

You'll learn how to build a reusable curry function that automatically transforms any multi-argument function into a curried version.

The Core Idea

Instead of manually currying functions one-by-one (as you did in previous lessons), you can write a generic curry helper that does the work for you. This helper inspects how many arguments a function expects, collects arguments one-by-one, and only executes the original function once all arguments are received.

Think of it like a vending machine that waits until you've inserted enough coins before dispensing your snack—it doesn't matter when you insert each coin, only that you eventually provide the total amount needed.

Building the Helper

function curry(fn) {
  return function curried(...args) {
    // If we've received enough arguments, call the original function
    if (args.length >= fn.length) {
      return fn(...args);
    }
    // Otherwise, return a new function waiting for more arguments
    return function(...nextArgs) {
      return curried(...args, ...nextArgs);
    };
  };
}

// Now curry ANY function automatically
const add = (a, b, c) => a + b + c;
const curriedAdd = curry(add);

console.log(curriedAdd(1)(2)(3));       // 6
console.log(curriedAdd(1, 2)(3));       // 6
console.log(curriedAdd(1)(2, 3));       // 6

The helper checks fn.length (the number of declared parameters) and accumulates arguments using the spread operator. Each partial application returns a new function until all arguments are collected.

Why This Matters

Now you can curry any function without manual rewriting, making functional composition and argument specialization effortless across your codebase.

Key Takeaway: A generic curry helper automates the currying process by checking argument count and recursively collecting arguments until the original function can be invoked.