Code Multiplexer
Bitwise Table Lookup

by Eric Fortis

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

Benefits:

  • It’s easier to read than nested conditionals.
  • It makes explicit the number of cases to test and review.
  • Performance gains.

Example

In Uxtly, a connection’s color varies when it’s selected, hovered, and their combinations.

Selected Hovered 0 0 0 1 1 0 1 1

As the colors are in an array, each particular color can be queried with bitwise operations. Namely, shifting-left one bit (<< 1) the selected boolean variable, and or’ing (|) it with the hovered one.

/* Bits: selected, hovered */
const colors = [
  grey,  // 00
  green, // 01
  blueA, // 10
  blueB  // 11
]
const color = colors[selected << 1 | hovered]

Let’s trace a demo:

selected = true, hovered = true would be index 3

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

Yes, it’s like a multiplexer.

Readability Comparison

Compare it with nested conditionals.

let color = '';
if (selected) {
  if (hovered) {
    color = blueB;
  } else {
    color = blueA;
  }
} else {
  if (hovered) {
    color = green;
  } else {
    color = grey;
  }
}

Or compare it with nested ternaries.

const color = selected
  ? hovered
    ? blueB 
    : blueA
  : hovered
    ? green
    : grey

Sponsored by: