Let's make a curry!
Saksham Malhotra
Posted on January 9, 2024
Currying is a technique in JavaScript that allows you to transform functions with multiple arguments into a sequence of functions, each taking one argument at a time. That is from
f(a, b, c)
tof(a)(b)(c)
.
This might sound overwhelming at first but should be very easy to understand with an example.
Suppose we want to multiply 2 numbers together. Assuming it is not straight forward, we can declare a function called multiply
as
function multiply(num1, num2) {
// pseudo complex logic
return num1 * num2;
}
But what if we want to generate variants which can either double or triple or quadruple a number?
One option could be to simply define each variant separately as
function double(num1) {
return multiply(2, num1);
}
Or we can be clever and use currying here
const generateMultiplier = function(multiplier) {
return function multiply(num) {
return multiplier * num;
}
}
This would give us the power to generate variants as we like
const double = generateMultiplier(2);
const result = double(2); // returns 4
Best of coding!
Posted on January 9, 2024
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.
Related
November 24, 2024
November 22, 2024