Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to raise an error, when the IF statement is TRUE?

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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));
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading