Javascript
Convert HEX to HSL
Generated by OpenAI text-davinci-003
/**
* Converts a hex color to its HSL value
* @param {string} hex - The hex color to be converted
* @returns {string} - The HSL value of the hex color
* */
const hexToHSL = (hex) => {
let result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);
let r = parseInt(result[1], 16);
let g = parseInt(result[2], 16);
let b = parseInt(result[3], 16);
r /= 255, g /= 255, b /= 255;
let max = Math.max(r, g, b), min = Math.min(r, g, b);
let h, s, l = (max + min) / 2;
if(max == min){
h = s = 0; // achromatic
}else{
let 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;
}
h = Math.round(h * 360);
s = Math.round(s * 100);
l = Math.round(l * 100);
return `HSL(${h}, ${s}%, ${l}%)`;
}
console.log(hexToHSL("#4BA37B")); // "HSL(153, 37%, 47%)"
This function takes in a hex color as a string argument. It then uses a regular expression to parse the hex color into its individual red, green, and blue components. These are stored as variables and converted to decimal numbers between 0 and 1 by dividing them by 255. The max and min values of the red, green, and blue components are then calculated.
The hue, saturation, and lightness values are then calculated based on the max and min values. The hue is calculated by determining which of the red, green, and blue components is the max value, and then calculating the difference between that value and the other two components. The saturation and lightness are calculated by determining the difference between the max and min values, and then dividing that by the sum of the max and min values.
Finally, the hue, saturation, and lightness values are rounded to the nearest integer and the resulting HSL value is returned.