I am trying to print the values inside the memo object, but I am getting undefined while is clear that there is values inside the memo object, or even iterating the object to get the values, please help.
let arr = [1, 2, 3, 4];
function iter(arr, n, memo = {}) {
if (n < arr.length) {
memo[n] = iter(arr, n 1);
}
// iterate memo object and print the values
// memo = { '0': { '1': { '2': [Object] } } }
for (let i in memo) {
console.log(memo[i]);
// I am getting undefined
}
// also here when I return the first value I am gettng undefined
//
return memo["0"];
}
console.log(iter(arr, 0));
CodePudding user response:
By doing
if(n < arr.length){
memo[n] = iter(arr,n 1)
}
and
return memo['0']
at the bottom of the function, this means that:
- You don't pass
memo
along in the recursive call, so you're creating a new object each timeiter
runs. Even if you fix that - - You return
memo['0']
- but that 0 index is only assigned to at the very end of all the recursive calls. (n
starts at 0, you enter recursion, then you eventually exit recursion, and finally at that point do you assign tomemo[0]
- not before - so before then, it's alwaysundefined
.)
If what you wanted was
memo = { '1': { '2': [Object] } }
then .reduceRight
would be more appropriate to produce that structure. (memo
isn't a good name because you aren't memoizing anything). The n
variable doesn't look to be accomplishing anything here that .reduceRight
can't handle by itself easier.
let arr = [1, 2, 3, 4];
function iter(arr, n) {
return arr.reduceRight((prevValue, prop) => ({ [prop]: prevValue }));
}
console.log(iter(arr, 0))
If you wanted to use explicit recursion here, then perhaps something like
let arr = [1, 2, 3, 4];
function iter(arr, n) {
return n === arr.length - 1
? arr[n]
: { [arr[n]]: iter(arr, n 1) };
}
console.log(iter(arr, 0));
CodePudding user response:
let arr = [1,2,3,4];
function iter(arr,n,memo = {}){
if(n < arr.length){
memo[n] = iter(arr,n 1,memo) iter(arr,n 1, memo)
}
for(let i in memo){
console.log(i)
}
}
console.log(iter(arr,0))