UI Drafter

Bitwise Table Lookup

Eric Fortis

This technique is similar to traditional table lookups, but it generates indices with bitwise operators.

Benefits:

  • It's easier to read than conditional branching.
  • It makes clear the number of cases to test and review.

Example

In UI Drafter, a connection's color varies if it's selected, hovered, and their combinations.

Selected Hovered 0 0 0 1 1 0 1 1

The colors are in an array:

// Bits: selected, hovered
const colors = [
  grey,  // 00
  green, // 01
  blueA, // 10
  blueB  // 11
];

…and can be queried as:

colors[selected << 1 | hovered]

Demo Trace

selected = true, hovered = true would be index 3

true << 1 | true
1 << 1 | 1
2 | 1
3

Sponsored by: