We have defined a function called countdown with one parameter (n). The function should use recursion to return an array containing the integers n through 1 based on the n parameter. If the function is called with a number less than 1, the function should return an empty array. For example, calling this function with n = 5 should return the array [5, 4, 3, 2, 1]. Your function must use recursion by calling itself and must not use loops of any kind.
function countdown(n){
if (n < 1){
return [];
}else{
const countArray = countdown(n - 1);
countArray.push(n);
return countArray;
}
}
I am getting the following errors:
countdown(10) should return [10, 9, 8, 7, 6, 5, 4, 3, 2, 1]
countdown(5) should return [5, 4, 3, 2, 1]
Global variables should not be used to cache the array.
3
Answers
You could use an optional argument to pass the result array into the recursive calls:
The spread is slooooow:
This works using the spread operator.
There are many possible ways of going about this… here is just one:
Here: I’ve used the following:
The spread operator unpacks elements of iterable objects such as arrays, sets, and maps into a list.
So the line
If we step through an example like
countdown(2)
it would look like this: