During a recent interview, I was given the task to create a function based on the code snippet below:
add(2,3,4)(5,6)(7,8); // Should yield 35
The code snippet above showcases a function called 'add' that can be invoked multiple times and can handle an infinite number of arguments per invocation. Ultimately, it is expected to return the total sum of all the arguments provided across all invocations.
Below is a partial solution for this problem, which requires a final invocation without any arguments.
/**
* @description
* infiniteAdd(2,3)(4,5)(6,7)()
* The above operation results in 27
*/
function infiniteAdd() {
// Creating closure for subsequent function invocations
var prevArgs = Array.prototype.slice.call(arguments);
return function() {
var currArgs = Array.prototype.concat.call(prevArgs, Array.prototype.slice.call(arguments));
if (arguments.length < 1) {
// Calculate sum when no arguments are passed
return Array.prototype.reduce.call(currArgs,
function(acc, curr) {
return acc + curr;
}
);
}
// Recursively call the main function until no more arguments are provided
return infiniteAdd.apply(null, currArgs);
}
}
console.log(infiniteAdd(2, 3)(4, 5)(6, 7)());