import { GumHexToRgb } from '../models'; /** * Removes hash from hex value * @param hex HEX color value */ const removeHash = (hex: string) => { const arr = hex.split(''); arr.shift(); return arr.join(''); }; /** * Expands shorthand HEX value (#FFF -> #FFFFFF) * @param hex HEX color value */ const expand = (hex: string) => hex .split('') .reduce( (accum: string[], value: string) => accum.concat([value, value]), [], ) .join(''); /** * Converts HEX color value to RGB * @param hex HEX color value */ export const hexToRgb: GumHexToRgb = (hex) => { if (hex.charAt && hex.charAt(0) === '#') { hex = removeHash(hex); } if (hex.length === 3) { hex = expand(hex); } const bigint = parseInt(hex, 16); const r = (bigint >> 16) & 255; const g = (bigint >> 8) & 255; const b = bigint & 255; return [r, g, b] as [number, number, number]; };