All files / internalHelpers _rgbToHsl.js

100% Statements 23/23
100% Branches 13/13
100% Functions 1/1
100% Lines 23/23
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52                      44x 44x 44x   44x 44x 44x   44x   7x 1x   6x         37x 37x 37x   9x 9x   17x 17x   11x 11x     37x 37x 18x   19x        
// @flow
 
import type {
  HslColor,
  HslaColor,
  RgbColor,
  RgbaColor,
} from '../types/color'
 
function rgbToHsl(color: RgbColor | RgbaColor): HslColor | HslaColor {
  // make sure rgb are contained in a set of [0, 255]
  const red = color.red / 255
  const green = color.green / 255
  const blue = color.blue / 255
 
  const max = Math.max(red, green, blue)
  const min = Math.min(red, green, blue)
  const lightness = (max + min) / 2
 
  if (max === min) {
     // achromatic
    if (color.alpha !== undefined) {
      return { hue: 0, saturation: 0, lightness, alpha: color.alpha }
    } else {
      return { hue: 0, saturation: 0, lightness }
    }
  }
 
  let hue
  const delta = max - min
  const saturation = lightness > 0.5 ? delta / (2 - max - min) : delta / (max + min)
  switch (max) {
    case red:
      hue = ((green - blue) / delta) + (green < blue ? 6 : 0)
      break
    case green:
      hue = ((blue - red) / delta) + 2
      break
    default: // blue case
      hue = ((red - green) / delta) + 4
      break
  }
 
  hue *= 60
  if (color.alpha !== undefined) {
    return { hue, saturation, lightness, alpha: color.alpha }
  }
  return { hue, saturation, lightness }
}
 
export default rgbToHsl