All files / internalHelpers _hslToRgb.js

100% Statements 33/33
96.3% Branches 26/27
100% Functions 3/3
100% Lines 33/33
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 53 54 55 56 57 58 59 60 61          102x       34x                 67x   13x       54x 54x 54x   54x 54x 54x   54x 21x 21x 33x 15x 15x 18x 2x 2x 16x 7x 7x 9x 7x 7x 2x 2x 2x     54x 54x 54x 54x 54x        
// @flow
 
type ConversionFunction = (red: number, green: number, blue: number) => string;
 
function colorToInt(color: number): number {
  return Math.round(color * 255)
}
 
function convertToInt(red, green, blue) {
  return `${colorToInt(red)},${colorToInt(green)},${colorToInt(blue)}`
}
 
function hslToRgb(
  hue: number,
  saturation: number,
  lightness: number,
  convert: ConversionFunction = convertToInt,
): string {
  if (saturation === 0) {
    // achromatic
    return convert(lightness, lightness, lightness)
  }
 
  // formular from https://en.wikipedia.org/wiki/HSL_and_HSV
  const huePrime = (hue % 360) / 60
  const chroma = (1 - Math.abs((2 * lightness) - 1)) * saturation
  const secondComponent = chroma * (1 - Math.abs((huePrime % 2) - 1))
 
  let red = 0
  let green = 0
  let blue = 0
 
  if (huePrime >= 0 && huePrime < 1) {
    red = chroma
    green = secondComponent
  } else if (huePrime >= 1 && huePrime < 2) {
    red = secondComponent
    green = chroma
  } else if (huePrime >= 2 && huePrime < 3) {
    green = chroma
    blue = secondComponent
  } else if (huePrime >= 3 && huePrime < 4) {
    green = secondComponent
    blue = chroma
  } else if (huePrime >= 4 && huePrime < 5) {
    red = secondComponent
    blue = chroma
  } else Eif (huePrime >= 5 && huePrime < 6) {
    red = chroma
    blue = secondComponent
  }
 
  const lightnessModification = lightness - (chroma / 2)
  const finalRed = red + lightnessModification
  const finalGreen = green + lightnessModification
  const finalBlue = blue + lightnessModification
  return convert(finalRed, finalGreen, finalBlue)
}
 
export default hslToRgb