How can I achieve these scenarios using function currying?
add(3,4)(3)
add(3)(4)(3)
add(3)(4,3)
I have read so many blogs not able to find this kind of scenario. can someone help me on this.
How can I achieve these scenarios using function currying?
add(3,4)(3)
add(3)(4)(3)
add(3)(4,3)
I have read so many blogs not able to find this kind of scenario. can someone help me on this.
Something like this?
var total = 0;
function add(){
// Add up every argument received
for (var i in arguments)
total += arguments[i];
return add;
}
add(3,4)(3);
console.log(total);
add(3)(4)(3);
console.log(total);
add(3)(4,3);
console.log(total);
If you do not want the function to depend on global variable, save the value as an attribute of add
function instead
function add(){
// Add up every argument received
for (var i in arguments)
add.total += arguments[i];
return add;
}
add.total = 0;
add.toString = function(){
var total = add.total;
add.total = 0;
return total;
};
var sum1 = add(3,4)(3);
alert( sum1 );
var sum2 = add(3)(4)(3);
alert( sum2 );
var sum3 = add(3)(4,3);
alert( sum3 );
I see two currying scenarios here:
1.
add(3,4)(3)
add(3)(4,3)
and
2.
add(3)(4)(3)
The first one you can address with:
function add() {
const args1 = Array.prototype.slice.call(arguments);
return function() {
const args2 = Array.prototype.slice.call(arguments);
return args1.concat(args2).reduce(function(a, i) { return a + i });
}
}
The second one with:
function add() {
const args1 = Array.prototype.slice.call(arguments);
return function() {
const args2 = Array.prototype.slice.call(arguments);
return function() {
const args3 = Array.prototype.slice.call(arguments);
return args1.concat(args2).concat(args3).reduce(function(a, i) { return a + i });
}
}
}
I did not find a solution to have a function which tackles both at the same time.