We need to create a function that would print the results for:
console.log(sum(1)(2)(3)(4)(5)(6)());
So this is how I did:
let res = 0;
function sum(a){
if(a){
res = res + a;
return sum; //Return the same function for next chain of actions
}else{
return res;
}
}
console.log(sum(1)(2)(3)());
Is there a way I can achieve this with a local res
? the problem I face with making it local is, it just gets reset in the next call.
I see some solutions like this:
function sum(a) {
return function(b){
if(!b){
return a;
}
return sum(a+b);
}
}
But the way I did appears more natural and intuitive to me and I just want to make that work with res
as local instead of gloabl.
2
Answers
You could do it like this:
The
innerSum
function maintains a closure over res. This allows res to retain its value across multiple calls toinnerSum
.Demo
You can make the
sum
an IIFE and putres
in the local scope. After that, when called with no arguments, reset theres
to0
to make it ready for the next call.It can also be shortened in a simpler but maybe cursed syntax: