Can you help me solve this interesting problem? I need a javascript function that can return the sum of all arguments passed to it, even when called multiple times.
I have identified different ways in which the function can be called -
sum(1, 2, 3, 4);
sum(1, 2)(3, 4);
sum(1, 2)(3)(4);
sum(1, 2, 3)(4);
sum(1)(2, 3, 4);
All these variations should work correctly and return the total of 10.
I have made an attempt at solving this issue, but my code only works for the first two function calls sum(1, 2, 3, 4)
and sum(1, 2)(3, 4)
. It fails for the other cases.
const arr = [];
function sum(...args) {
if (args.length === 4) {
return args.reduce((acc, curr) => {
return (acc = acc + curr);
}, 0);
} else {
arr.push(...args);
return function(...args) {
arr.push(...args);
return sum(...arr);
};
}
}
I would appreciate any assistance with this problem as it's really getting frustrating.
Thank you!