Search code examples
javascripttypescriptconditional-operator

How to simplify this ternary expression?


I wonder if there is a simpler way to write this, or is it already in it's most basic form?

A ? (B && C) : B

Solution

  • Assuming all are booleans, it says that to return true, either A and B and C must be true, or A must be false and B must be true (with C irrelevant). This can be written as A && B && C || !A && B.

    From this we can see that the result can only be true if B is true, so we can extract B from both parts: B && (A && C || !A) or the equivalent B && (!A || A && C).

    This can be further reduced to B && (!A || C). We now have one less term: A, B and C each occur once, so it could be considered simpler. Although because of the negation, not everyone might find it simpler to understand.

    Truth tables (created using https://truth-table.com):

    Truth tables