fix: input validation in hexToRgb, pre-initialize h in rgbToHsl

This commit is contained in:
Ferdinand
2026-04-01 16:18:01 +02:00
parent 6bb0b6a37e
commit 8aacaa1d8f

View File

@@ -1,6 +1,7 @@
// Hex → RGB
export function hexToRgb(hex) {
const h = hex.replace('#', '');
if (!/^[0-9a-fA-F]{3}$/.test(h) && !/^[0-9a-fA-F]{6}$/.test(h)) return null;
const n = parseInt(h.length === 3
? h.split('').map(c => c + c).join('')
: h, 16);
@@ -16,10 +17,10 @@ export function rgbToHex({ r, g, b }) {
export function rgbToHsl({ r, g, b }) {
r /= 255; g /= 255; b /= 255;
const max = Math.max(r, g, b), min = Math.min(r, g, b);
let h, s;
let h = 0, s = 0;
const l = (max + min) / 2;
if (max === min) {
h = s = 0;
// h and s remain 0 (achromatic)
} else {
const d = max - min;
s = l > 0.5 ? d / (2 - max - min) : d / (max + min);