I came across this interesting problem. Write a javascript function that returns sum of all the arguments passed to it, through multiple calls to that same function.
Here are the ways 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 the calls above should work and return 10.
Here's what I have written so far, but it only works for first two function calls sum(1, 2, 3, 4)
and sum(1, 2)(3, 4)
and shits the bed for rest of it.
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);
};
}
}
Someone please help me, this is driving me nuts.
Thanks!