I need to test to see if exactly two out of three booleans are true.
Something like this:
if ((a && b && !c) || (a && !b && c) || (!a && b && c)) {
// success
}
Is this the most direct way to go about this? Does anyone know of a shortcut/shorthand?
Boolean values are values that evaluate to either true or false , and are represented by the boolean data type. Boolean expressions are very similar to mathematical expressions, but instead of using mathematical operators such as "+" or "-", you use comparative or boolean operators such as "==" or "!".
To check if a value is of boolean type, check if the value is equal to false or equal to true , e.g. if (variable === true || variable === false) . Boolean values can only be true and false , so if either condition is met, the value has a type of boolean. Copied!
We use the compare() method of the BooleanUtils class to compare two boolean values. The method takes two values and returns true if both the values are the same. Otherwise, it returns false .
boolean isEqual = Boolean. equals(bool1, bool2); which should return false if they are not equal, or true if they are.
To check if exactly two are equal to true
:
[a, b, c].filter(Boolean).length === 2;
References:
Array.prototype.filter()
.Boolean()
.If you add the values you can check if the result is 2
if ((a + b + c) == 2) {
// do something
}
I would go this readable (IMO) way:
let conditions = [a && b && !c, a && !b && c, !a && b && c]
if(conditions.filter(c => c).length === 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