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 ];
}