The Task:
Write a recursive function, `range`, that takes a start and an end and returns
an array of all numbers in that range, exclusive. If the end number is less than
the start, return an empty array.
It was my first day with recursion and I found getting the range of 2 numbers easy, however, for me getting the range BETWEEN two numbers took me hours. X.X
This works. But I tried to understand it by logging it and... Well. Impossible, for me.
Again, getting the range was easy but the code broke WITHOUT the else statement and when I changed
else if (startNum <= endNum)
to
else if (startNum < endNum) {
(To not get the last number aka endNum)
This code is clearly not the ideal answer. Could someone explain what on Earth is going on here/a better solution? I was honestly going to call it quits for the night when I decided to try another else statement and then paste
else {
console.log("Random Else statement that made it work")
return range(startNum+1, endNum)
}
And it, somehow, worked.
What I have tried:
function range(startNum, endNum) {
if (startNum > endNum) {
return [];
} else if (startNum < endNum) {
console.log(range(startNum+1, endNum))
var rangeArray = range(startNum+1, endNum);
console.log(startNum + " <-- Start End ---> " + endNum)
rangeArray.unshift(startNum);
return rangeArray;
} else {
console.log("Random Else statement that made it work")
return range(startNum+1, endNum)
}
};