Spot the bug - #171: Hex Palette Blender

Color mixer function keeps generating invalid hexadecimal string values.

function parseHexColor(hex) {
  const clean = hex.replace('#', '');
  const num = parseInt(clean, 16);
  return {
    r: (num >> 16) & 255,
    g: (num >> 8) & 255,
    b: num & 255
  };
}

function blendRgb(c1, c2, ratio) {
  const clamped = Math.min(Math.max(ratio, 0), 1);
  return {
    r: Math.round(c1.r + (c2.r - c1.r) * clamped),
    g: Math.round(c1.g + (c2.g - c1.g) * clamped),
    b: Math.round(c1.b + (c2.b - c1.b) * clamped)
  };
}

function formatHexColor(rgb) {
  const r = rgb.r.toString(16);
  const g = rgb.g.toString(16);
  const b = rgb.b.toString(16);
  return `#${r}${g}${b}`;
}

function generatePaletteSteps(startHex, endHex, totalSteps) {
  const start = parseHexColor(startHex);
  const end = parseHexColor(endHex);
  const palette = [];
  const stepFactor = 1 / (totalSteps - 1);

  for (let i = 0; i < totalSteps; i++) {
    const blended = blendRgb(start, end, i * stepFactor);
    palette.push(formatHexColor(blended));
  }

  return palette;
}

const mysticSwatches = generatePaletteSteps('#050a0f', '#e0f810', 8);

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

It’s when the RGB values are less than 16. The toString(16) will give you a single digit, but hex colors need two digits for each R, G, B. You need to pad with a leading zero if the value is less than 16. Like r.toString(16).padStart(2, '0').

Wait yeah, that’s exactly it. the padStart(2, '0') is the missing piece. i’ve definitely shipped that bug before lol.

Spot the Bug answer: The formatHexColor function does not pad single-digit hexadecimal color components with a leading zero, leading to invalid 3-digit or 5-digit hex codes.

The fix:

return `#${r.padStart(2, '0')}${g.padStart(2, '0')}${b.padStart(2, '0')}`;

Why:
Hexadecimal color codes require each component (red, green, blue) to be represented by exactly two characters. When a component’s value is less than 16 (e.g., 5), its toString(16) representation is a single digit (‘5’). The function concatenates these single digits directly, resulting in incorrect hex strings like ‘#5a0f’ instead of ‘#050a0f’.

First-answer leaderboard

  1. @emmawalter5 - 11 (firsts) :trophy:
  2. @kirupa - 8 (firsts)
  3. @Apexcodes - 6 (firsts)
  4. @adnanahmed - 2 (firsts)