I have written code to achieve
sum(1)(2) //3
the code looks like:
function sum(a) {
return function(b) {
return a+b
}
}
But I didn't work out the second question, which is how to achieve any arbitrary number of chain function call like:
sum(1)(2) == 3
sum(5)(-1)(2) == 6
sum(6)(-1)(-2)(-3) == 0
sum(0)(1)(2)(3)(4)(5) == 15
Normally you'd do something like this:
var add = function(a,b){
return a+b;
};
var sum = function(){
return [].reduce.call(arguments, add);
}
And then you can write:
sum(1,2,3,4); // 10
But it is possible to hack the functionality you're after:
var sum = function(x){
var f = function(y){
return sum(x+y);
};
f.valueOf = function(){
return x;
};
return f;
};
sum(1)(2)(3)(4); // 10
Just don't do it in production code please!
You can't do this - how does the sum
function know whether you want it to return the answer or another function?
You could do something along these lines though:
sum(0)(1)(2)(3).result()
Implemented like this:
var sum = (function(){
var total = 0;
var f = function(n){
total += n;
return f;
};
f.result = function(){
return total;
};
return f;
}());
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With