How can I check if any of the variables is greater than 0 from given variable in Typescript?
How can I rewrite below code so that it's more elegant/concise?
checkIfNonZero():boolean{
const a=0;
const b=1;
const c=0;
const d=0;
//Regular way would be as below.
//How can this use some library instead of doing comparison for each variable
if(a>0 || b>0 || c>0 || d>0){
return true;
}
return false;
}
Greater Than ( > ) It is used to check for the greater value or variable containing greater value as compared with the other number or variable. If the provided number or a variable is greater than the given number or variable. Then, the Greater Than operator will return True. Else, it will return false.
The greater than or equal operator ( >= ) returns true if the left operand is greater than or equal to the right operand, and false otherwise.
You can combine the variables into an array and then run some on it:
return [a, b, c, d].some(item => item > 0)
You can combine the &&
operator with the ternary operator
like this:
(a && b && c && d > 0) ? true : false // will return true if all integers are more than 0
jsFiddle: https://jsfiddle.net/AndrewL64/6bk1bs0w/
OR you can assign the variables to an array and use Array.prototype.every() like this:
let x = [a, b, c, d]
x.every(i => i > 0) // will return true if all integers are more than 0
jsFiddle: https://jsfiddle.net/AndrewL64/6bk1bs0w/1/
OR to make the above even shorter, you can directly place the values in an array and use every
on the array directly like this:
[0, 1, 0, 0].every(i => i > 0); // will return false since all integers are not more than 0
jsFiddle: https://jsfiddle.net/AndrewL64/6bk1bs0w/3/
OR you can make a reusable function once and run it multiple times with just one line like this:
function moreThanOne(...args){
// Insert any of the above approaches here but reference the variables/array with the word 'arg'
}
moreThanOne(3,1,2,0); // will return false as well as alert false
moreThanOne(3,1,2,4); // will return true as well as alert true
jsFiddle: https://jsfiddle.net/AndrewL64/6bk1bs0w/2/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With