Recurse once per item
You have a list of numbers and you want their total. A loop will do it, but look
at the shape first: the sum of a list is the first number plus the sum of
everything after it. [1, 2, 3] is 1 + (2 + 3), and 2 + 3 is 2 + (3), and
the last number is itself.
Peel one card off the top of a deck and you are holding a smaller deck. The task has not changed — only its size. That is the self-similar step: take the first item, then add the sum of the rest.
You need a case that stops. When the list is empty there is nothing left to add,
so the sum is 0. That is the base case, and it answers itself without calling
anything.
Shrink the input on every call by dropping the first element. A shorter list each time means the empty list is always reachable.
Then trust the recursive call. When you write sum(numbers.slice(1)), assume it
already returns the sum of the rest — you only do the small piece in front of
you, this number plus that answer:
function sum(numbers) {
if (numbers.length === 0) {
return 0;
}
return numbers[0] + sum(numbers.slice(1));
}
Each call handles one number and hands the rest to a smaller copy of itself.
Export sumList from index.js. It returns the total of a list of numbers,
with an empty list summing to 0.
Challenge
A list of numbers hides a smaller list inside it: drop the first number and what
is left is the same problem again. Export a sumList function from index.js
that adds the list up by recursing once per element.
sumList takes an array of numbers and returns their total. An empty list sums
to 0, and that base case returns before any addition happens.