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:
@@ -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
|
||||
|
||||
Reference in New Issue
Block a user