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