Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if any one of the variable is greater than 0

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;
}
like image 769
RV. Avatar asked May 16 '18 22:05

RV.


People also ask

How do you check if a variable is greater than a number python?

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.

How do you write greater than or equal to in Javascript?

The greater than or equal operator ( >= ) returns true if the left operand is greater than or equal to the right operand, and false otherwise.


2 Answers

You can combine the variables into an array and then run some on it:

return [a, b, c, d].some(item => item > 0)

like image 61
AnilRedshift Avatar answered Oct 29 '22 02:10

AnilRedshift


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/

like image 21
AndrewL64 Avatar answered Oct 29 '22 03:10

AndrewL64