How can I refactor the following using the ternary operator syntax instead?
let divisor = 2;
let isPrime = (num) => {
if (num % divisor === 0) return false;
else divisor++;
return true;
};
console.log(`prime is ${isPrime(83)}`);
You can use conditional operator with comma operator following :
at exp2
let divisor = 2; let isPrime = num => num % divisor === 0 ? false : (++divisor, true); console.log(`prime is ${isPrime(83)}`);
You can increment the number and convert it to a Boolean, because numbers that are not 0 will be converted to true
(num) => num % divisor ? // > 0 == true : 0 == false
!!(++divisor) // increment and convert to boolean
:
false
let divisor = 2; const isPrime = (num) => num % divisor ? !!(++divisor) : false; console.log(`prime is ${isPrime(83)}`);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.