Wednesday, February 19, 2025

JavaScript, JavaScript Currying Explained

JavaScript Currying Explained
What is currying in JavaScript. Explain by some examples.
Answer: Currying in JavaScript is a technique where a function that takes multiple arguments is transformed into a series of functions that each take a single argument. It allows you to partially apply a function by fixing some arguments and returning a new function that takes the remaining arguments.
Here's a simple example to illustrate currying:javascript
// A non-curried function that adds three numbers
function add(a, b, c) {
return a + b + c;
}
console.log(add(1, 2, 3)); // Output: 6
// A curried version of the same function
function curryAdd(a) {
return function(b) {
return function(c) {
return a + b + c;
};
};
}
console.log(curryAdd(1)(2)(3)); // Output: 6

In the curried version 'curryAdd', you first call the function with the first argument '1'. This returns a new function that takes the second argument '2', which in turn returns another function that takes the third argument '3'. Finally, this function returns the sum of all three arguments.You can use ES6 arrow functions to make the curried function more concise:
javascript
const curryAdd = a => b => c => a + b + c;
console.log(curryAdd(1)(2)(3)); // Output: 6
Currying can be useful in scenarios where you want to create specialized functions from a generic function.
javascript
// A function to multiply two numbers
const multiply = a => b => a * b;
// Create a specialized function to double a number
const double = multiply(2);
console.log(double(5)); // Output: 10
console.log(double(10)); // Output: 20
// Create a specialized function to triple a number
const triple = multiply(3);
console.log(triple(5)); // Output: 15
console.log(triple(10)); // Output: 30

In this example, 'multiply' is a curried function that returns a function to multiply by a fixed number. 'double' and 'triple' are specialized functions created from 'multiply' by partially applying it with '2' and '3', respectively.Libraries like Lodash provide utilities to easily curry functions. Here's how you can use Lodash's 'curry' function:
javascript
const _ = require('lodash');
// A non-curried function that adds three numbers
function add(a, b, c) {
return a + b + c;
}
// Create a curried version of the add function
const curriedAdd = _.curry(add);
console.log(curriedAdd(1)(2)(3)); // Output: 6
console.log(curriedAdd(1, 2)(3)); // Output: 6
console.log(curriedAdd(1)(2, 3)); // Output: 6

Lodash's 'curry' function allows you to call the curried function with any combination of arguments, and it will still work correctly.Currying transforms a function with multiple arguments into a series of functions that each take a single argument. It allows for partial application of functions, making code more modular and reusable.

No comments:

Post a Comment

Hot Topics