dimanche 16 août 2020

Only evaluate parts of a condition when the corresponding flag is set

For example, I have flag1, flag2, flag3,..., flagN as boolean values for flags.

I need to write an if statement like this: If flagK is false, then turn off the "K" part of the condition:

if (condition0 && (flag1 && condition1) && (flag2 && condition2) ... && (flagN && conditionN))
{
   // do something
} 

// For example, if flag 2 is false then the condition should only be:
if (condition0 && (flag1 && condition1) && ... && (flagN && conditionN))
{
   //do something}
}

Particularly, given an example like this (for demo only not my real problem):

const divby2 = false; //if this is false, then ignore the **i%2 === 0** below
const divby3 = true;
const divby4 = true;
const divby5 = true;
//......const divbyN....

const array = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,42,45,241,526]
 
array.forEach((i) => {
    if(i >= 0 && (divby2 && i%2 === 0) && (divby3 && i%3 === 0)) {
      console.log(i) // output here should be 3,6,9,12 instead of nothing
    }
  }
)

Example Result: Example Result

Aucun commentaire:

Enregistrer un commentaire