Skip to content

Instantly share code, notes, and snippets.

@imgsrc
Created August 12, 2018 16:35
Show Gist options
  • Save imgsrc/de0b42b8cb9bb495583129ef28aa82d9 to your computer and use it in GitHub Desktop.
Save imgsrc/de0b42b8cb9bb495583129ef28aa82d9 to your computer and use it in GitHub Desktop.
converter hex to rgb / rgb to hex
type Color = { r: number, g: number, b: number };
function hexToRgb(hex: string): Color {
if (hex.length === 3) {
let [hr, hg, hb] = hex.split(''); // ['F', '0', '0']
return hexToRgb(`${hr}${hr}${hg}${hg}${hb}${hb}`);
}
let [r, g, b] = [0, 2, 4]
.map(offset => hex.substring(offset, offset + 2)) // ['FF', '00', '00']
.map(hex => parseInt(hex, 16)); // [255, 0, 0]
return {r, g, b};
}
function rgbToHex(r: number, g: number, b: number): string {
return [r, g, b]
.map(dec => dec.toString(16)) // ['ff', '0', '0']
.map(hex => hex.length === 1 ? `0${hex}` : hex) // ['ff', '00', '00']
.join('');
}
console.log(hexToRgb('00f'));
console.log(rgbToHex(255, 0, 0));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment