I was trying to solve a puzzle which takes 'n' arguments and then computes sum.
function add(arg1) {
let total=arg1;
const func = function(...args){
if(!args[0]) return total;
total += args[0];
return func;
}
return func;
}
console.log(add(1)(2)(3)()); // => Should output 6
Question: Using the same logic above example, I am trying to do this:
What if I want to do something like
sum(1)(2)(3) => should give 6
If i do sum(1) => Should output 1
sum(1)(2) => should output 3 and so forth.
This is what I've tried:
function sum2(num) {
let total = num;
const fn = function(...args) {
if(args[0]) total += args[0];
return total;
}
return fn();
}
console.log(sum2(1)) //=> Works
console.log(sum2(1)(2))// => Fails