Question 73
Question
Describe the concept of currying and its applications.
Answer
What is Currying?
Currying is a powerful function transformation technique that takes a function with multiple arguments and converts it into a sequence of functions, each taking a single argument.
Imagine you have a function add(x, y)
that adds two numbers. With currying, you'd transform it into:
function add(x) {
return function(y) {
return x + y;
};
}
const add5 = add(5); // Now add5 is a function that takes one argument and adds 5 to it
console.log(add5(3)); // Output: 8 (because 5 + 3 = 8)
Key Points:
Gradual Argument Application: Each call to a curried function returns a new function until all arguments are provided. This allows you to "partially apply" functions, creating specialized versions for specific use cases.
Function Composition Made Easier: Currying aligns beautifully with function composition because you can readily combine curried functions.
Applications of Currying:
Partial Application: Create customized functions with some arguments pre-filled. For example:
add5(3)
effectively creates a new function that adds 5 to any given number.More Readable Code: Currying can make complex function calls more understandable by breaking them down into smaller, more manageable steps.
Code Reusability: Generate specialized functions from a single curried function template. This promotes code reuse and reduces redundancy.
Example: Applying Currying to Object Construction
function createCar(brand) {
return function(model) {
return function(color) {
return { brand, model, color };
};
};
}
const myCar = createCar('Ford')('Mustang')('Red');
console.log(myCar); // Output: { brand: 'Ford', model: 'Mustang', color: 'Red' }
Last updated