- It is a mechanism of evaluating function with multiple parameters into sequence of functions with single parameter. It means, Instead of passing all parameters at one time, takes first parameter and return a new function that takes second and return a new function, until all parameters have been fulfilled.
- It is useful to create reusable event handling code
- It is helpful to avoid passing same variable again and again
- It is helpful to create a higher order function
ES5 Normal Function
var say = function(wish, name) {
console.log(wish + ", " + name);
};
say("Hi", "Nolan");
// output : Hi,Nolan
Convert above function into nested function
ES5 Currying Function
var saycurrying = function(wish) {
return
function(name) {
console.log(wish +
", " + name);
};
};
var sayHi = saycurrying ("Hi");
sayHi ("Nolan"); // output : Hi, Nolan
sayHi ("Christopher"); // output : Hi,
Christopher
Direct Calling Currying Function
saycurrying(“Hi”)(“Nolan”) // output : Hi, Nolan
ES5 Currying Function- Example2
function sum(x) {
return (y) => {
return (z) => {
return x + y +
z;
};
};
}
var firstparam=sum(2);
/
var secondparam = firstparam(3);
var result = secondparam(4); // output : 9
Direct calling: sum(2)(3)(4); // output : 9
ES6 Currying Function- Example1
var saycurrying = (wish) => (name) => {
console.log(wish +
", " + name);
};
var sayHi = saycurrying ("Hi");
sayHi ("Nolan"); // output : Hi, Nolan
Direct
calling: saycurrying
("Hi")(“Nolan”); // output : Hi, Nolan
ES6 Currying Function- Example2
renderHtmlTag = tagName => content =>
`<${tagName}>${content}</${tagName}>`
renderDiv = renderHtmlTag('div')
renderDiv(“This is sample div”)
renderH1 = renderHtmlTag('h1')
renderH1 (“This is sample H1”)
Direct
calling: renderHtmlTag("div")(“This
is sample div”);
Happy Coding :)
No comments:
Post a Comment