I want to use recursion from reverse. I am trying to add all the values in the recursion to a memo object.
I am using visual studio code.
I have an error in the line
if( key==n) return memo[n];
In the last iteration it raised undefined error.
But up to the last iteration the line is not giving any error. I am printing the key and n variable.
When I check inside the if clause there is a value in the key but there is no key variable.
inside if, the key does not exists.
Any idea?
const factorial = (x=0,n=0, memo={})=> {const key = x ;}
console.log(key);
console.log(n);
if (key==0 || key==1) {memo[key]=1;}
if(key!=0 && key!=1) {memo[key]=memo[key-1]*key;}
if( key==n) return memo[n];
factorial(x=key+1,n,memo)
};
console.log(factorial(x=0,n=3));
this states that problem is in the if clause
if(1==1 ) return memo[key];
this replacement again raised error
if(key==key) return memo[n];
>Solution :
Just remove the end } bracket in the first line.
const factorial = (x=0,n=0, memo={})=> {
const key = x ;
console.log(key);
console.log(n);
if (key==0 || key==1) {
memo[key]=1;
}
if(key!=0 && key!=1) {
memo[key]=memo[key-1]*key;
}
if( key==n) return memo[n];
factorial(x=key+1,n,memo)
};
console.log(factorial(x=0,n=3));