new class js -advanced
This commit is contained in:
@@ -0,0 +1,13 @@
|
||||
function sumArrayIndex(arr, index = 0) {
|
||||
// Base case: when index is greater than or equal to the length of the array return 0
|
||||
if (index >= arr.length) {
|
||||
return 0;
|
||||
}
|
||||
// Recursive case: add the current element to the sum of the rest of the array
|
||||
return arr[index] + sumArrayIndex(arr, index + 1);
|
||||
}
|
||||
|
||||
// Test cases
|
||||
console.log(sumArrayIndex([1, 2, 3, 4, 5])); // => 15
|
||||
console.log(sumArrayIndex([10, -2, 33, 47])); // => 88
|
||||
console.log(sumArrayIndex([])); // => 0
|
||||
Reference in New Issue
Block a user