'Alternatives to (A && B) || (!A && !B) conditions . Flag switching behaviour
I'm refactoring some code where there are a bunch of statements like this:
const color = isDark
? isOdd
? 'white'
: 'black'
: isOdd
? 'black'
: 'white'
Note that we could swap isDark with isOdd and get the exact same results.
The code essentially has two possible outcomes depending on a condition –being odd in the example–, and a flag that switches de behaviour –isDark in the example–.
I don't find that code very readable, so I was looking for alternatives. The ones I found are:
const first = (isDark && isOdd) || (!isDark && !isOdd) ? 'white' : 'black'
const second = isDark === isOdd ? 'white' : 'black'
The first statement is probably more explicit about what's going on. The second statement is a shorter version, but probably the least readable.
What are other alternatives in this scenario?
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
