Ad

Mainly introduced a delta and directly extracted and normalized
r, g, and b

Code
Diff
  • function rgbToHsv(rgb) {
      const [r, g, b] = rgb.map(value => value / 255);
      const v = Math.max(r, g, b);
      const min = Math.min(r, g, b);
      const delta = v - min;
      const s = v === 0 ? 0 : delta / v;
    
      let h = 0;
      if (s !== 0) {
        if (v === r) {
          h = (g - b) / delta;
        } else if (v === g) {
          h = 2 + (b - r) / delta;
        } else {
          h = 4 + (r - g) / delta;
        }
        h *= 60;
        if (h < 0) h += 360;
      }
    
      return [Math.round(h), Math.round(s * 100), Math.round(v * 100)];
    }
    • function rgbToHsv(rgb) {
    • let r = rgb[0] / 255, g = rgb[1] / 255, b = rgb[2] / 255;
    • const [r, g, b] = rgb.map(value => value / 255);
    • const v = Math.max(r, g, b);
    • const min = Math.min(r, g, b);
    • const s = v === 0 ? 0 : (v - min) / v;
    • const delta = v - min;
    • const s = v === 0 ? 0 : delta / v;
    • let h = 0;
    • if (s !== 0) {
    • if (v === r) {
    • h = (g - b) / (v - min);
    • h = (g - b) / delta;
    • } else if (v === g) {
    • h = 2 + (b - r) / (v - min);
    • h = 2 + (b - r) / delta;
    • } else {
    • h = 4 + (r - g) / (v - min);
    • h = 4 + (r - g) / delta;
    • }
    • h *= 60;
    • if (h < 0) h += 360;
    • }
    • return Array.of(Math.round(h), Math.round(s * 100), Math.round(v * 100));
    • }
    • return [Math.round(h), Math.round(s * 100), Math.round(v * 100)];
    • }