I am trying to make a function such that if I call either,
curriedSum(10, 12)(21);
curriedSum(13)(21)(12, 12);
curriedSum(12)(12, 30);
should return correct answer.
I am trying to make it dynamic i.e. there can be more than 3 calls, can be any number of calls.
This is the code that I am trying
if(!Array.prototype.sum){
Array.prototype.sum = function(){
return this.reduce((acc, item) => acc + item, 0)
}
}
let curriedSum = (...args) => {
if(args.length === 0) {
return 0;
}else {
let currSum = args.sum();
return (...innerArgs) => {
if(innerArgs.length == 0){
return currSum;
}
return curriedSum(currSum, ...innerArgs);
}
}
}
console.log(curriedSum(2)(23)(12, 29));
It consoles [Function (anonymous)]
but if I call curriedSum(2)(23)(12, 29)()
then it returns the correct value, so I want to make such that I don’t need to call that extra ()
and it should be dynamic too.