function moreRecurse(arr, n){
if(n == 0) return []
let finalArray = moreRecurse(arr.map(el => el * 2), n - 1)
finalArray.push(arr)
return finalArray
}
moreRecurse([1, 2, 3], 4)//[ [ 8, 16, 24 ], [ 4, 8, 12 ], [ 2, 4, 6 ], [ 1, 2, 3 ] ]
I’m getting it a little better, thanks for you replies guys. As for the case above, my question is: how do each function -while getting back to the original one- have access to arr? Each time, as the callStack deflates, I push arr to the finalArray, and then I return it (finalArray I mean), but I’m not returning arr itself. Is that a default behavior of the recursive function to ‘return’ its values? Arr is mapped and then -under the hood- gets available to the functions that follows? To make myself clearer:
let count = 5
let array = [1, 2, 3]
let finalArray = []
while(count > 0){
finalArray.push(array.map(el => el * 2)) //arr is always the same of course, therefore is always the same array that gets pushed to the final one
count--
}
console.log(finalArray)//[ [ 2, 4, 6 ], [ 2, 4, 6 ], [ 2, 4, 6 ], [ 2, 4, 6 ], [ 2, 4, 6 ] ]
A solution could be:
let counter = 5
let another_array = [1, 2, 3]
let another_finalArray = []
while(counter > 0){
another_array = another_array.map(el => el * 2)
another_finalArray.push(another_array)
counter--
}
console.log(another_finalArray)
/*
[ [ 2, 4, 6 ],
[ 4, 8, 12 ],
[ 8, 16, 24 ],
[ 16, 32, 48 ],
[ 32, 64, 96 ] ]
*/
That’s the point where I’m getting confused; I cannot see the process, in my recursion, of ‘redefining’ the array before pushing it into the finalArray.
Break. Before posting I took my time and I tried to figure it out. What happens is something like that right?
/*
//the number is the nth line
(((1)2)3).map() 4th line => our final array is ready
//before getting to the final line, at each line arr is mapped and -as a wave- gets finally to the 4th line, where our function stops running and returns our final result...
*/