Looking for a way to solve this problem by recursing sum()
. Right now, the code works, but I am supposed to call sum()
more than once, and it should not mutate the input array.
var sum = function(array) {
if(array.length === 0){
return 0;
}
function add(array, i){
console.log(array[i]);
if(i === array.length-1){
return array[i];
}
return array[i] + add(array, i+1);
}
return add(array, 0);
};
sum([1, 2, 3, 4, 5, 6]) //21
A one-liner that meets all your requirements:
var sum = function(array) {
return (array.length === 0) ? 0 : array[0] + sum(array.slice(1));
}
// or in ES6
var sum = (array) => (array.length === 0) ? 0 : array[0] + sum(array.slice(1));
// Test cases
sum([1,2,3]); // 6
var s = [1,2,3];
sum(s); // 6
sum(s); // 6
sum
of the remainder of the array - at some point, these successive calls will eventually result in a call to sum([])
, the answer to which you already know. That is exactly what the code above does.array.slice(1)
creates a shallow copy of the array starting from the first element onwards, and no mutation ever occurs on the original array. For conciseness, I have used a ternary expression.Breakdown:
sum([1,2,3])
-> 1 + sum([2,3])
-> 1 + 2 + sum([3])
-> 1 + 2 + 3 + sum([])
-> 1 + 2 + 3 + 0
-> 6
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With