'Shorthand for if/else in javascript
I wrote the function to check if a given number is positive, negative, or zero. Is there a shorthanded way?
Is it possible to test the condition with map (using object to index the conditions)? i was inspired by second solution in this question but not sure how it applies here.
const numCheck = (num) => {
if (num == 0) {
return "zero";
} else {
return num > 0 ? "positive" : "negative";
}
};
const num1 = 3;
console.log(numCheck(num1));
Solution 1:[1]
In the solution below, the numCheck() method is tested by using the Array.prototype.map() method, considering three possible situations.
const numCheck = (num) => {
return (num == 0) ? "zero" : ((num > 0) ? "positive" : "negative");
};
const numbers = [1, -1, 0];
console.log(numbers.map(number => numCheck(number)));
Solution 2:[2]
you can do that, simply use Math.sign() :
const numCheck = n => ['negative','zero','positive'][1+Math.sign(n)]
console.log( numCheck( 4 ) )
console.log( numCheck( 0 ) )
console.log( numCheck( -3 ) )
Solution 3:[3]
A shorter solution:
var numCheck = (num) => num == 0 ? "zero" : num > 0 ? "positive" : "negative";
const num1 = 3;
console.log(numCheck(num1));
Solution 4:[4]
Inspired by Mister Jojo answer but without Math.sign
const sign = x => ['negative','zero','positive'][1 + (x > 0) - (x < 0)]
console.log(sign(10)) // positive
console.log(sign(0)) // zero
console.log(sign(-20)) // negative
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | |
| Solution 3 | Faly |
| Solution 4 | whynot |
