Confused on how does this work? Maybe the wording is throwing me off?

Just wanting to know how they got to this solution as the statement they wrote made me think different.

Exercise.
We have defined a function named rangeOfNumbers with two parameters. The function should return an array of integers which begins with a number represented by the startNum parameter and ends with a number represented by the endNum parameter. The starting number will always be less than or equal to the ending number. Your function must use recursion by calling itself and not use loops of any kind. It should also work for cases where both startNum and endNum are the same.

My original solution…
function rangeOfNumbers(startNum, endNum) {
if (startNum <= endNum) {
return ;
} else {
const arr = rangeOfNumbers();
arr.push(startNum, endNum);
return arr;
}
};

console.log(rangeOfNumbers(1, 10));

Correct solution…
function rangeOfNumbers(startNum, endNum) {
if (endNum - startNum === 0) {
return [startNum];
} else {
var numbers = rangeOfNumbers(startNum, endNum - 1);
numbers.push(endNum);
return numbers;
}
}

if (startNum <= endNum) {
  return [];
}

Isn’t this always going to be true the first time you call the function? When will you ever make the recursive call?

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.