Hi @cgf04df,
IDK if this is what are you looking for, but I think that python tutor is really useful:
https://pythontutor.com/live.html#mode=edit
I also wrote a short faq
about recursion (is not the same exercise but I think is similar enough, look at: 5.- Why I'm Getting [4,3,2,1] ?
):
code
function rangeOfNumbers(startNum, endNum) {
if(startNum === endNum) {
return [endNum];
} else {
let arr = rangeOfNumbers(startNum + 1, endNum);
arr.push(startNum);
return arr;
}
}
let result = rangeOfNumbers(1,4);
console.log(result);
// [ 4, 3, 2, 1 ]
1.- What happens when the base case is evaluated as false?
The function calls itself:
Steps: 4,6,8
2.- What happens when the base case is evaluated as true?
Returns an array:
Step: 10
3.- The Array, where does it come from?
From the base case:
Step: 10
4.- Why can I push startNum to arr?
Because after the base case is evaluated as true, arr is an array:
Step: 11
5.- Why I’m Getting [4,3,2,1] ?
Because JavaScript uses a “stack” (LIFO, last in first out):
Steps: 10, 13, 16, 19
6.- How can I get [1,2,3,4]?
Replace push
with unshift
function rangeOfNumbers(startNum, endNum) {
if(startNum === endNum) {
return [endNum];
} else {
let arr = rangeOfNumbers(startNum + 1, endNum);
arr.unshift(startNum); // <- here
return arr;
}
}
let result = rangeOfNumbers(1,4);
console.log(result);
// [ 1, 2, 3, 4 ]
7.- Related topics:
- nested (function) calls
- call stack
8.- You can use python tutor
to see step by step how the function is executed:
https://pythontutor.com/live.html#mode=edit
Cheers and happy coding
Notes:
- If you know spanish, I recorded a video explaining recursion step by step:
- I also wrote a blog post (it has 27 images)
https://diegoperezm.github.io/blog/recursion.html