Currying is converting a single function of arguments into functions with a single argument each. So you can say Currying is a way to reduce functions of more than one argument to functions of one argument.
Here in Currying function we also uses the property of closures because we access the variables outside the scope of a function.
Here is and example of doing two number addition in JavaScript with simple function :
1
2
3
|
var add = function(x, y) {
return x + y;
};
|
No if you write this with currying function in JavaScript :
1
2
3
4
5
|
var curriedAdd = function(x) {
return function(y) {
return x + y;
};
};
|
Here is another which can give you more clarity on Currying function in JavaScript.
1
2
3
4
|
// Simple JavaScript function
var quadratic = function(a, b, c, d) {
return a * d * c + b * a + d;
};
|
1
2
3
4
5
6
7
8
9
10
|
// Curried function example
var curriedQuadratic = function(a) {
return function(b) {
return function(c) {
return function(x) {
return a * d * c + b * a + d;
};
};
};
};
|
...