Update 02_recursive_sum.js (#168)

First, congratulations for the work, the book is very instructive.

In this case, as described in the book, if the list is empty it returns zero, otherwise we apply recursion.

Co-authored-by: Aditya Bhargava <bluemangroupie@gmail.com>
This commit is contained in:
Rosana Rezende
2022-11-18 17:58:08 -03:00
committed by GitHub
parent 788c54e92b
commit cf78943cef

View File

@@ -5,9 +5,9 @@
* @param {Array} array Array of numbers
* @returns {number} Sum of the numbers
*/
function sumRecursive(array) {
if (array.length == 1) return array[0];
return array[0] + sumRecursive(array.slice(1));
function sumRecursive(arr) {
if (arr.length == 0) return 0;
return arr[0] + sumRecursive(arr.slice(1));
}
console.log(sumRecursive([1, 2, 3, 4])); // 10