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

Recognize anything which is not a number and return null or None

I was writing a factorial function and I wanted to add a logic that returns null or None if the user puts anything into the argument instead of numbers like symbols (@#!) or letters (s,z).
how can I recognize them and immediately stop my program and return null or None?
I know some ways but they will make my code really ugly and hard to read and long.

function factorial(n){

let num = Number(n);

// make num - 1 each time and push it into the list
let miniaturizedNum = [];
for (num; num > 0; num--){
    miniaturizedNum.push(num);
}

// Multiply the finalresult with the numbers in the list
// and finalresault is 1 because zero multiplied by anything becomes zero
let finalResault = 1;
for (let i = 0; i < miniaturizedNum.length; i++){
    finalResault *= miniaturizedNum[i];
}

return finalResault;

}

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

>Solution :

Assuming

  • you want to accept strings representing a number and convert them to number

  • you want do avoid non integers and negative numbers since you’re calcolating the factorial

    if( typeof( n ) !== 'string' &&
        typeof( n ) !== 'number' &&
        ( '' + n ).match(/^[0-9]+$/) === null ) {
        return null;
    }
    
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