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