Skip to content

Conversions/RgbHslConversion: rgbToHsl mutates (and returns) its input array instead of a copy #1907

@aimasteracc

Description

@aimasteracc

Description

Conversions/RgbHslConversion.js::rgbToHsl mutates its input array. It aliases the argument with let colorHsl = colorRgb (no copy) and then overwrites colorHsl[0..2] in place, so the caller's RGB array is destroyed and replaced with the HSL result.

const rgbToHsl = (colorRgb) => {
  ...
  let colorHsl = colorRgb        // <- alias, NOT a copy
  ...
  colorHsl[0] = red / limit      // mutates caller's array
  ...
  colorHsl[0] = Math.round(hue)  // final HSL written back into the input array
  colorHsl[1] = Math.round(saturation * 100)
  colorHsl[2] = Math.round(luminance * 100)
  return colorHsl
}

The returned value is the same array object as the input, so a caller that still needs its RGB values loses them.

To Reproduce (verified with Node):

const input = [24, 98, 118]
const result = rgbToHsl(input)
// result            -> [193, 66, 28]   (correct HSL)
// input             -> [193, 66, 28]   <- the caller's RGB array was overwritten
// input === result  -> true            <- same object, not a copy

Expected behavior

rgbToHsl returns a new HSL array and leaves the input RGB array unchanged (a conversion function should not have side effects on its argument).

Actual behavior

The input array is mutated in place and is returned as the result (input === result), so the original RGB data is destroyed.

Suggested fix

Work on a copy instead of aliasing the input:

let colorHsl = [...colorRgb]

The HSL math itself is correct; only the in-place mutation of the argument needs fixing.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions