How Currying Works
How Currying Works
Section titled “How Currying Works”Introduction
Section titled “Introduction”Currying transforms a function that takes multiple arguments into a chain of functions, each accepting a single argument.
The Core Idea
Section titled “The Core Idea”// Normal function — takes all arguments at oncefunction add(a, b, c) { return a + b + c;}add(1, 2, 3); // 6
// Curried version — each argument returns a new functionfunction curriedAdd(a) { return function(b) { return function(c) { return a + b + c; }; };}curriedAdd(1)(2)(3); // 6Manual Curry Implementation
Section titled “Manual Curry Implementation”function curry(fn) { return function curried(...args) { if (args.length >= fn.length) { // Enough arguments — call the original function return fn.apply(this, args); } else { // Not enough — return a function waiting for more return function(...moreArgs) { return curried.apply(this, args.concat(moreArgs)); }; } };}
// Usagefunction sum(a, b, c) { return a + b + c;}
const curriedSum = curry(sum);curriedSum(1)(2)(3); // 6curriedSum(1, 2)(3); // 6curriedSum(1)(2, 3); // 6Arrow Function Shortcut
Section titled “Arrow Function Shortcut”// Manual currying with arrowsconst add = a => b => c => a + b + c;add(1)(2)(3); // 6
const greet = greeting => name => `${greeting}, ${name}!`;const sayHello = greet('Hello');sayHello('Alice'); // 'Hello, Alice!'sayHello('Bob'); // 'Hello, Bob!'Why Curry Matters
Section titled “Why Curry Matters”Currying enables partial application and creates reusable, specialized functions:
const multiply = a => b => a * b;
const double = multiply(2); // specialized: times 2const triple = multiply(3); // specialized: times 3
double(5); // 10triple(5); // 15Summary
Section titled “Summary”- Currying:
fn(a, b, c)→fn(a)(b)(c) - Each call returns a new function until all arguments are collected
- Enables partial application and function specialization
- Arrow functions make currying syntax clean