This technique is similar to traditional table lookups, but generating indices with bitwise operators.
- It's easier to read than conditional branches.
- It makes clear the number of cases to test and review.
In UI Drafter, a connection's color varies if
hovered, and their combinations.
The colors are in an array:
// Bits: selected, hovered const colors = [ grey, // 00 green, // 01 blueA, // 10 blueB // 11 ];
…which can be queried as:
colors[selected << 1 | hovered]
selected = true,
hovered = true would be index
true << 1 | true 1 << 1 | 1 2 | 1 3