BY Simmi Kava
JavaScript: CURRYING
What is currying in JS?
Currying is a process of evaluating a function with multiple arguments and turning it into a sequence of functions, each with single argument only i.e converting an n-ary function into the unary function form.
Why use currying?
- Code reusability
- To achieve Function Composition (A process of combining simple functions to build more complicated ones)
- Easy to maintain as our code implementation will be smaller and more readable.
Can you explain it with an Example?
Certainly,
Let's look at an example to convert an input number to string using the radix provided.
//Without Currying
var print = (number,radix) => number.toString(radix);
console.log(print(123,16)); //7b
console.log(print(123,2)); //1111011
//With Currying
var print = (radix) => (number) => number.toString(radix);
var hex = print(16);
var binary = print(2);
console.log(hex(123)); //"7b"
console.log(binary(123)); //"1111011"
Here, print
is a function, which takes 1 argument which is radix
, (16 for hex and 2 for binary etc.). number
is the input number which needs to be converted and the lambda function
will print the input number in the given numeral format.
BY Simmi Kava
Like | Comment | Save | Share |
ARCHIVES
2024
2023
2022
2021