0

On an FCC exercise I came with this bad code:

function rangeOfNumbers(startNum, endNum) {
  if (endNum < startNum) {
    return [];
  } else {
    let recurs = rangeOfNumbers(++startNum, endNum)
    recurs.unshift(startNum - 1);
    return recurs;
  }
};

Really bad code apart, what called my attention was that ++startNum worked and startNum++ was InternalError: too much recursion. Looked some other posts and YT videos, but still couldn't understand it.

Here is the proper code:

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

or even better:

function rangeOfNumbers(startNum, endNum) {
  return startNum === endNum
    ? [startNum]
    : [...rangeOfNumbers(startNum, endNum - 1), endNum ];
}
Tiago N
  • 1
  • 2
  • even betterer `const range = (a, b) => a > b ? [] : [ a, ...range(a + 1, b) ]` – Mulan Jan 03 '21 at 19:21
  • startNum++ generates an infinite recursion when ```endNum >= startNum``` because the recursion is called with the same parameters (unchanged), verifies the same condition and calls itself again, and again... – alainlompo Jan 03 '21 at 20:44

0 Answers0