aiao-io/aiao

View on GitHub
libs/color/src/lib/rgb-hsb.ts

Summary

Maintainability
A
0 mins
Test Coverage
import { ColorHSB, ColorRGB } from './interface';

// eslint-disable-next-line @typescript-eslint/naming-convention
export const HSBToRGB = (hsb: ColorHSB): ColorRGB => {
  const { h, s, b: v } = hsb;
  let r!: number;
  let g!: number;
  let b!: number;
  const i = Math.floor(h / 60);
  const f = hsb.h / 60 - i;
  const p = v * (1 - s);
  const q = v * (1 - f * s);
  const t = v * (1 - (1 - f) * s);
  switch (i % 6) {
    case 0:
      r = v;
      g = t;
      b = p;
      break;
    case 1:
      r = q;
      g = v;
      b = p;
      break;
    case 2:
      r = p;
      g = v;
      b = t;
      break;
    case 3:
      r = p;
      g = q;
      b = v;
      break;
    case 4:
      r = t;
      g = p;
      b = v;
      break;
    case 5:
      r = v;
      g = p;
      b = q;
      break;
  }
  return {
    r: Math.round(r * 255),
    g: Math.round(g * 255),
    b: Math.round(b * 255)
  };
};

// eslint-disable-next-line @typescript-eslint/naming-convention
export const RGBToHSB = (RGB: ColorRGB): ColorHSB => {
  let { r, g, b } = RGB;
  r /= 255;
  g /= 255;
  b /= 255;

  const max = Math.max(r, g, b);
  const min = Math.min(r, g, b);
  const d = max - min;
  let h!: number;
  const s = max === 0 ? 0 : d / max;
  const v = max;

  if (max === min) {
    h = 0;
  } else {
    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: h * 360, s, b: v };
};