convert rgb to hsl in typescript

You can convert an RGB color value to an HSL color value in TypeScript by using the following code:

index.ts
function rgbToHsl(r: number, g: number, b: number): [number, number, number] {
  r /= 255;
  g /= 255;
  b /= 255;

  const max = Math.max(r, g, b);
  const min = Math.min(r, g, b);
  let h: number;
  let s: number;
  const l = (max + min) / 2;

  if (max == min) {
    h = s = 0;
  } else {
    const d = max - min;
    s = l > 0.5 ? d / (2 - max - min) : d / (max + min);

    switch (max) {
      case r:
        h = (g - b) / d + (g < b ? 6 : 0);
        break;
      case g:
        h = (b - r) / d + 2;
        break;
      case b:
        h = (r - g) / d + 4;
        break;
    }

    h /= 6;
  }

  return [h, s, l];
}
628 chars
35 lines

Here is an example of how you could use this function:

index.ts
const rgbColor = [22, 145, 230];
const [h, s, l] = rgbToHsl(rgbColor[0], rgbColor[1], rgbColor[2]);
console.log(`HSL color value: ${h}, ${s}, ${l}`);
150 chars
4 lines

This would output the following:

index.ts
HSL color value: 0.589041095890411, 0.8454545454545455, 0.5019607843137255
75 chars
2 lines

gistlibby LogSnag