52. What is function currying? Explain with the help of an example.
Function currying is a technique used in functional programming where a single function is converted into multiple functions by adding arguments incrementally. It allows us to break down complex functions into smaller, more manageable ones, making them easier to read and understand.
In currying, a function takes one argument at a time and returns a new function that takes the remaining argument(s). This way, we can create multiple functions from a single function by calling it with different arguments or no arguments at all.
function multiply(a, b) {
return a * b;
}
// Currying the multiply function
const multiplyByA = multiply;
const multiplyByB = multiply;
// Using curried functions
console.log(multiplyByA(3)(4)); // Output: 12
console.log(multiplyByB(3)(4)); // Output: 12
In this example, the `multiply` function takes two arguments `a` and `b`. We curried the function by creating two new functions `multiplyByA` and `multiplyByB`, which simply call the original `multiply` function with different arguments. Now we can use these curried functions to perform multiplication without having to define a separate function for each number.
function sum(a, b) {
return a + b;
}
const sumByA = sum;
const sumByB = sum;
console.log(sumByA(2)(3)); // Output: 5
console.log(sumByB(2)(3)); // Output: 5
In this example, the `sum` function takes two arguments `a` and `b`. We curried the function by creating two new functions `sumByA` and `sumByB`, which simply call the original `sum` function with different arguments. Now we can use these curried functions to perform addition without having to define a separate function for each number.
In summary, function currying is a technique used in functional programming where a single function is converted into multiple functions by adding arguments incrementally. It allows us to break down complex functions into smaller, more manageable ones, making them easier to read and understand.