I have some code like this
var a = returnsABoolean();
var b = returnsABoolean();
if (!a || !b) {
} else {
doStuff();
}
How would I invert the test in the if-statement such that I can rewrite this as
var a = returnsABoolean();
var b = returnsABoolean();
if (someExpression) {
doStuff();
}
In other words, what test should I replace someExpression
with to preserve the existing behaviour?
You need to apply De Morgan's theorem. Which states:
!A || !B == !(A && B)
Therefore your test can be re-written as:
if (a && b) {
doStuff();
}
Basically, applying De Morgan's theorem you first rewrite your statement as:
if ( ! (a && b) ) {
} else {
doStuff();
}
Since we now want to invert !(a&&b)
we simply remove the not:
if ( (a && b) ) {
doStuff();
}
De Morgan's law states that you can rewrite !a || !b
as !(a&&b)
This also works the other way: !a && !b
can be rewritten as !(a||b)
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