Can someone visually explain what’s going on here please.
var stack = [];
function countDown(int) {
stack.push(int);
if (int === 1) {
return 1;
}
return countDown(int - 1);
}
function multiplyEach() {
// Remove the last value of the stack
// and assign it to the variable int
int = stack.pop();
x = stack.length;
// Base case
if (x === 0) {
return int;
}
// Recursive case
else {
stack[x - 1] = int * stack[x - 1];
return multiplyEach();
}
}
// Call the function
countDown(7);
// And then print out the value returned by multiplyEach()
console.log(multiplyEach());
I sorta understand that’s it’s creating a stack and them multiplying everything together but I can’t visualize it.
Then:
Stack[x-1] is getting me
This is a two part algorithm.
First
countDown(n)fills the arraystackwith values fromndown to1, sostack = [n, n-1, n-2, ..., 3, 2, 1]. The return value ofcountDownis never used and so thereturnstatement can be ignored. The only thing that matters is that it fills thestackarray as explained.Second,
multiplyEachrepeatedly takes the last element of the stack, removes it, and multiplies it with the next last element in the array:In other words, the algorithm calculates the factorial of the number
ngiven tocountDown.