xxxxxxxxxx
// It is also called nested function is ecmascript
const multiply = (a) => (b) => a*b;
multiply(3)(4); //Answer is 12
const multipleBy5 = multiply(5);
multipleBy5(10); //Answer is 50
xxxxxxxxxx
//Currying:
It is a technique in functional programming, transformation of the
function of multiple arguments into several functions of a single
argument in sequence. It is also called nested function is ecmascript
//Without currying
function calculateVolume(length, breadth, height) {
return length * breadth * height;
}
//With Currying
function calculateVolume(length) {
return function (breadth) {
return function (height) {
return length * breadth * height;
}
}
}
xxxxxxxxxx
//No currying
function volume(w, h, l) {
return w * h * l;
}
volume(4, 6, 3); // 72
//Currying
function volume(w) {
return function(h) {
return function(l) {
return w * h* l;
}
}
}
volume(4)(6)(3); // 72
xxxxxxxxxx
// function curring
let num = (num1) => {
return (num2) => {
return (num3) => {
console.log(num1, num2, num3);
}
}
}
num(10)(20)(30);
//output = 10 20 30
//
xxxxxxxxxx
const curry = (fn) => {
const curried = (args) => (
args.length >= fn.length
? fn(args)
: (rest) => curried(args, rest)
);
return curried;
};
const add = (x, y) => x + y;
const curriedAdd = curry(add);
curriedAdd(1)(2); // 3
xxxxxxxxxx
// Currying :
//- Currying is an advanced technique of working with functions.
function sum(a) {
return function (b) {
return function (c) {
return function (d) {
console.log("sun is:::", a + b + c + d);
};
};
};
}
sum(5)(7)(3)(20);
xxxxxxxxxx
// currying
let currying = (a) => {
return (b) => {
return (c) => {
return a + b + c;
};
};
};
console.log(currying(1)(2)(3)); // 6
xxxxxxxxxx
const curry = (fn, arity = fn.length, args) =>
arity <= args.length ? fn(args) : curry.bind(null, fn, arity, args);
curry(Math.pow)(2)(10); // 1024
curry(Math.min, 3)(10)(50)(2); // 2
xxxxxxxxxx
It is a technique in functional programming, transformation of the
function of multiple arguments into several functions of a single
argument in sequence. It is also called nested function is ecmascript
//Without currying
function calculateVolume(length, breadth, height) {
return length * breadth * height;
}
//With Currying
function calculateVolume(length) {
return function (breadth) {
return function (height) {
return length * breadth * height;
}
}
}
xxxxxxxxxx
// Currying in JavaScript
// Currying is a technique in functional programming where a function is transformed into a sequence of functions, each taking a single argument.
// Here's an example of currying in JavaScript:
// Original function
function add(a, b, c) {
return a + b + c;
}
// Curried version
function curryAdd(a) {
return function(b) {
return function(c) {
return a + b + c;
};
};
}
// Usage
console.log(add(1, 2, 3)); // Output: 6
const curriedAdd = curryAdd(1);
console.log(curriedAdd(2)(3)); // Output: 6