Spot the bug - #97: Theme Color Parser

Color helper has one tiny bug.

function normalizeHex(hex) {
  const value = hex.startsWith('#') ? hex : '#' + hex;
  return value.slice(0, 6);
}

console.log(normalizeHex('#12abef'));

Reply with what is broken and how you would fix it.

Is it the range used by slice?

Close, but the range isn’t the bug by itself. slice(0, 6) counts from index 0, and the # is sitting right there at index 0. So you’re keeping the # plus only 5 hex chars, not 6.

1 Like

Spot the Bug answer: slice(0, 6) cuts off the last hex digit because it counts the leading # as one of the 6 characters, truncating a valid 6-digit hex code to 5 digits plus the hash

The fix:

return value.slice(0, 7);

Why:
A normalized hex color needs the # plus 6 characters, totaling 7 characters. Slicing to 6 keeps the # and only 5 digits, so ‘#12abef’ becomes ‘#12abe’, dropping the final ‘f’.


Nobody got this one. It was a sneaky one.

Close but not quite:

@kirupa - Doesn’t identify the actual fix (slice(0,7)) or clearly explain that the # is counted in the 6 characters, just vaguely gestures at slice.