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.
>Solution :
You can make the sum an IIFE and put res in the local scope. After that, when called with no arguments, reset the res to 0 to make it ready for the next call.
const sum = (() => {
let res = 0;
return function (a) {
if (typeof a === 'number') {
res = res + a;
return sum;
} else {
const temp = res;
res = 0;
return temp;
}
}
})();
console.log(sum(1)(2)(3)());
console.log(sum(1)(2)(3)(4)());
It can also be shortened in a simpler but maybe cursed syntax:
const sum = (res => a => {
if (typeof a === 'number') {
res = res + a;
return sum;
}
try {
return res;
} finally {
res = 0;
}
})(0);
console.log(sum(1)(2)(3)());
console.log(sum(1)(2)(3)(4)());