Q10: Implement Infinite Curried Addition sum(1)(2)(3)...()
Create a function that continuously accumulates numbers across chained function calls until called with no arguments to signal termination.
Infinitely Curried Sum
function sum(a) {
return function(b) {
if (b !== undefined) {
return sum(a + b);
}
return a;
};
}
console.log(sum(1)(2)(3)()); // 6
console.log(sum(5)(10)()); // 15💡 Each invocation returns a new sum function wrapping the updated total until b === undefined triggers the final total.
Key Takeaways
- Uses closure state to accumulate sum values across chained calls.
- Terminates recursive currying when invoked without arguments (b === undefined).
Knowledge Check
What acts as the base termination signal for ending the sum currying chain above?