As most of us know we can create a simple function like this.
function calc(a,b){
return a+b
}
calc(1,1); //returns 2
We can also make something like this
function calc(a){
return function(b){
return a+b
}
}
calc(1)(1); //returns 2
What about if we had multiple arguments?
function calc() {
function r(arg) {
var a = [];
for(var i = 0, l = arg.length; i < l; i++){
a[i] = arg[i];
}
return a.reduce(function(p, c) {
return p + c;
});
}
var res = r(arguments);
return function() {
res += r(arguments);
return res;
}
}
This works for calc(1,2)(1)
but it doesn't for calc(1,2,1)
Is there a way to combine both versions?
That means that when calling
calc(1,1)
we could also call calc(1)(1)
and both would still return 2.
Or calc(1,2,3)
calc(1,2)(3)
calc(1)(2,3)
would all return 6