Hi @daniel_Landau,
Two ideas are expressed in that line of code:
1.- A recursive definition of sum
2.- How to “access” a limited number of element(s) of an array using an index number
We can express the same ideas in other ways:
2.- How to “access” elements of an array (without using an index number)
To avoid the use of a index number, we can use the first and rest
approach.
The idea is mimic when people take things out of a box: they usually take them out one a a time (first), leaving the other things (rest) inside the box (array).
You can implement first and rest
in JS using a destructuring assignment[0] :
let arr = ["A","B","C","D","E"];
const [first, ...rest] = arr;
console.log("first:",first);
console.log("rest:",rest);
// first: A
// rest: [ 'B', 'C', 'D', 'E' ]
Using that approach you can access every element of an array:
As you can see in the gif
, if you apply first and rest
on an empty array you get undefined
and an empty array
(infinite):
let arr = [];
const [first, ...rest] = arr;
console.log("first:",first);
console.log("rest:",rest);
// first: undefined
// rest: []
To avoid that, you can use a condition.
1.- A recursive definition of sum
We can define sum
recursively (using first and rest
) as:
/**
* Returns the sum of every number in the array
* If the array is empty, return 0;
* @param {array} arr - the array of numbers
* @returns {number} - the sum of every number in the array or zero
*/
function sum(arr) {
if(arr.length === 0) return 0; // A condition (to avoid infinite recursive calls)
const [first, ...rest] = arr;
return first + sum(rest);
}
console.log(sum([0])); // 0
console.log(sum([1])); // 1
console.log(sum([0,1])); // 1
console.log(sum([1,2])); // 3
console.log(sum([1,-1])); // 0
As you can see, the above sum
is applied to every element of the array.
To limit to n
elements:
function sum(arr, n) {
const [first, ...rest] = arr;
if (n <= 0) return 0; // I changed the base case
return first + sum(rest, n-1); // without n-1 the base case is never reached
}
console.log(sum([1], 0)); // 0
console.log(sum([2, 3, 4], 1)); // 2
console.log(sum([2, 3, 4, 5], 3)); // 9
Conclusion
a.- I think that a sum
function that apply to every element of the array is easier to understand than a sum
function that only apply to some elements of the array.
b.- The part “… that returns the sum of the first n elements of an array arr” seems superfluous and arbitrary.
c. I read :
function sum(arr) {
if(arr.length === 0) return 0;
const [first, ...rest] = arr;
return first + sum(rest);
}
As:
The sum of all elements of an array is: the first element of the array plus the (result of the) sum of the rest of elements of the array.
Cheers and happy coding
Notes:
[0] Destructuring assignment - JavaScript | MDN