skip to Main Content

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];

2

Answers


  1. The extra curly bracket at the end is the issue. Please check below corrected code.

    const factorial = (x = 0, n = 0, memo = {}) => {
      const key = x;
      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];
      return factorial((x = key + 1), n, memo);
    };
    console.log(factorial((x = 0), (n = 5)));
    
    

    Although its not the optimal code but can do the job.
    Why not simply iterate and multiply.

    Login or Signup to reply.
  2. 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));
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search