Currying
Currying is a technique where a function that takes multiple arguments is transformed into a series of functions that each take a single argument.
1. The Analogy: The Personalized Coffee Order
Imagine you are ordering a coffee at a high-end cafe.
- Normal Function: You shout your entire order at once: "Large, Oat Milk, Vanilla Latte!"
- Curried Function: The barista asks you step-by-step:
- "What Size would you like?" (Large)
- "What kind of Milk?" (Oat)
- "Any Flavors?" (Vanilla)
The benefit? You can "save" your size and milk once, and then just change the flavor for your friends' orders!
2. Coding Example: The Logger
The Normal Way
function log(level, message) {
console.log(`[${level}] ${message}`);
}
log("ERROR", "Database Connection Failed");
log("ERROR", "API Timeout");The Curried Way
const log = level => message => {
console.log(`[${level}] ${message}`);
};
// You can create specialized "partial" functions
const errorLog = log("ERROR");
errorLog("Database Connection Failed");
errorLog("API Timeout");3. Why it matters in Coding
- Reusability: You can create specialized versions of a general function by "fixing" some of the arguments.
- Readability: It makes your code more declarative. Instead of
log("ERROR", msg), you seeerrorLog(msg). - Composition: Currying makes it much easier to pipe data through multiple functions because each function is waiting for exactly one input.
Real-Life Coding Scenario: The API Request
Imagine a function request(baseUrl, endpoint, data).
Using currying, you can "pre-configure" the baseUrl for your production API and create a apiClient(endpoint, data) function that you use everywhere in your app.
Summary
| Concept | Action | Analogy |
|---|---|---|
| Normal | All arguments at once | Fast Food Order |
| Curried | One argument at a time | Step-by-Step Customization |
Currying turns your complex functions into flexible, reusable templates!