As we were learning before, functions in javascript are
- Treated as sub-programs (execution context)
- First class objects (they have methods & properties)
Currying is basically:
function (a,b,c) --> function (a)(b)(c)
1. Currying using closures๐
function mix(f) { //closure, f is batter here
return function(a) {
return function(b) {
return f(a, b);
};
};
}
function batter(a, b) {
return a + b;
}
cook=mix(batter)
console.log(cook('flour ')('banana puree'));
2. Currying using function methods- bind()๐
As we have discussed before, bind()
is function method used to get a function copy to be used with fixed arguments or this
reference.
function multiply(a , b){
console.log(a)
console.log(b)
return a*b
}
getTwice=multiply.bind(this, 2)
console.log(getTwice(7))
We can change the number but getTwice will have a=2
fixed.
Currying requires the function to have a fixed number of arguments.
โญRead about functional programming concepts here.
I just had to link this one:
โญClosures, currying & functions in js
Top comments (0)