TheAlgorithms/JavaScript · error · Error

red should be between 0 and 255

Error message

red should be between 0 and 255

What it means

Thrown by rgbToHsv when red is below 0 or above 255. It is the first of three ordered per-channel guards (red, green, blue). Channel values are expected as integers in the standard 8-bit RGB range.

Source

Thrown at Conversions/RgbHsvConversion.js:50

  const chroma = value * saturation
  const hueSection = hue / 60
  const secondLargestComponent = chroma * (1 - Math.abs((hueSection % 2) - 1))
  const matchValue = value - chroma

  return getRgbBySection(hueSection, chroma, matchValue, secondLargestComponent)
}

/**
 * Conversion from the RGB-representation to the HSV-representation.
 *
 * @param red Red-component of the color.
 * @param green Green-component of the color.
 * @param blue Blue-component of the color.
 * @return The tuple of HSV-components.
 */
export function rgbToHsv(red, green, blue) {
  if (red < 0 || red > 255) {
    throw new Error('red should be between 0 and 255')
  }

  if (green < 0 || green > 255) {
    throw new Error('green should be between 0 and 255')
  }

  if (blue < 0 || blue > 255) {
    throw new Error('blue should be between 0 and 255')
  }

  const dRed = red / 255
  const dGreen = green / 255
  const dBlue = blue / 255
  const value = Math.max(Math.max(dRed, dGreen), dBlue)
  const chroma = value - Math.min(Math.min(dRed, dGreen), dBlue)
  const saturation = value === 0 ? 0 : chroma / value
  let hue

View on GitHub (pinned to 5c39e87a9a)

Solutions

  1. Clamp and round each channel: Math.max(0, Math.min(255, Math.round(red))).
  2. Validate Number.isFinite(red) && red >= 0 && red <= 255 upstream.
  3. Rescale 16-bit/float color sources to 0-255 before calling.

Example fix

// before
rgbToHsv(300, 0, 0)
// after
const clamp8 = (c) => Math.max(0, Math.min(255, Math.round(c)))
rgbToHsv(clamp8(300), 0, 0)
Defensive patterns

Strategy: validation

Validate before calling

if (!Number.isFinite(red) || red < 0 || red > 255) {
  throw new Error('red must be an integer in [0,255]')
}
rgbToHsv(red, green, blue)

Type guard

const isChannel8 = (c) => Number.isFinite(c) && c >= 0 && c <= 255

Try / catch

try {
  rgbToHsv(red, green, blue)
} catch (e) {
  if (/red should be between/.test(e.message)) {
    return rgbToHsv(Math.max(0, Math.min(255, Math.round(red))), green, blue)
  }
  throw e
}

Prevention

When it happens

Trigger: Calling rgbToHsv(300, 0, 0), rgbToHsv(-5, 0, 0), or rgbToHsv(256, 128, 128). NaN slips through the comparison but any concrete out-of-range value fails.

Common situations: Out-of-gamut values from an additive color blend; floating results that rounded up to 256; negative values from a difference computation; values from a 16-bit color source not rescaled.

Related errors


AI-assisted analysis of TheAlgorithms/JavaScript@5c39e87a9a (2026-08-13). Data as JSON: /api/errors/4302f8a99529eb9c. Report an issue: GitHub.