Currying is a transformation of functions that translates a function
from callable as f(a, b, c) into callable as f(a)(b)(c).
consider simple add function
//normal function
function Add(a,b)
{
return a+b;
}
lets convert into to currying:
Code:
function AddByCurring(a) {
return function (b) {
return a + b;
};
}
let result = AddByCurring(5)(6);
console.log(result);
Output:
11
Consider another code snippet below
Code:
//currying in javascript
let data = [
{ name: "sangram", email: "sangram@gmail.com" },
{ name: "saurabh", email: "saurabh@gmail.com" },
];
function Filter(key) {
return function (object) {
return object[key];
};
}
let funcGetName = Filter("name");
let nameResult = data.map(funcGetName);
console.log(nameResult);
let funcGetEmail = Filter("email");
let emailResult = data.map(funcGetEmail);
console.log(emailResult);
Output:
[ 'sangram', 'saurabh' ]
[ 'sangram@gmail.com', 'saurabh@gmail.com' ]
Another example of currying:
function Avg(...n)
{
return function cncat(...m)
{
n = n.concat(m)
let sum =0
for(let i=0;i < n.length;i++)
{
sum = sum + n[i]
}
return sum/n.length;
}
}
let avgVal = Avg(5,11)
let an = avgVal(8,8)
console.log("AVG:" + an);
Output:
AVG:8
No comments:
Post a Comment