Skip to content

Commit e1dc94f

Browse files
fix: rgbToHsl no longer mutates its input array
rgbToHsl aliased its argument with colorHsl = colorRgb instead of copying it, then overwrote colorHsl in place and returned that same array, destroying the caller's original RGB values. Copy the input with [...colorRgb] instead, and add a regression test asserting the input is left unchanged.
1 parent 5c39e87 commit e1dc94f

2 files changed

Lines changed: 8 additions & 1 deletion

File tree

Conversions/RgbHslConversion.js

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -22,7 +22,7 @@ const rgbToHsl = (colorRgb) => {
2222
throw new Error('Input is not a valid RGB color.')
2323
}
2424

25-
let colorHsl = colorRgb
25+
let colorHsl = [...colorRgb]
2626

2727
let red = Math.round(colorRgb[0])
2828
let green = Math.round(colorRgb[1])

Conversions/test/RgbHslConversion.test.js

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -40,4 +40,11 @@ describe('RgbHslConversion', () => {
4040
])('Should return the error message.', (colorRgb, expected) => {
4141
expect(() => rgbToHsl(colorRgb)).toThrowError(expected)
4242
})
43+
44+
test('Should not mutate the input array.', () => {
45+
const colorRgb = [24, 98, 118]
46+
const result = rgbToHsl(colorRgb)
47+
expect(colorRgb).toEqual([24, 98, 118])
48+
expect(result).not.toBe(colorRgb)
49+
})
4350
})

0 commit comments

Comments
 (0)