Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

invert a boolean expression

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?

like image 200
Georgio Avatar asked Dec 20 '22 10:12

Georgio


2 Answers

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();
}

Why does it work?

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();
}
like image 134
slebetman Avatar answered Jan 04 '23 15:01

slebetman


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)

like image 37
Brennan Avatar answered Jan 04 '23 14:01

Brennan