Skip to content

Instantly share code, notes, and snippets.

@Naedri
Last active August 9, 2022 14:03
Show Gist options
  • Save Naedri/0e78b902891fd0417d57e2302b105d68 to your computer and use it in GitHub Desktop.
Save Naedri/0e78b902891fd0417d57e2302b105d68 to your computer and use it in GitHub Desktop.
Color conversion and tool with RGB & hexadecimal code.
// Working in all environments
// https://stackoverflow.com/a/39077686
/**
* Converting RGB to hex
* @param r red
* @param g green
* @param b blue
* @returns Hexacode color
* @example rgbToHex(0, 51, 255); // '#0033ff'
*/
export const rgbToHex = (r: number, g: number, b: number): string => {
return (
'#' +
[r, g, b]
.map((x) => {
const hex = x.toString(16);
return hex.length === 1 ? '0' + hex : hex;
})
.join('')
);
};
/**
* Converting hex to RGB
* Works also with shorthand hex triplets such as "#03F".
* @param hex Hexacode color
* @returns RGB color object {r, g, b}
* @example hexToRgb("#0033ff"); // {r:0, g:51, b:255}
* @example hexToRgb("#03f"); // {r:0, g:51, b:255}
*/
export const hexToRgb = (hex: string): { r: number; g: number; b: number } | null => {
const result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);
return result
? {
r: parseInt(result[1], 16),
g: parseInt(result[2], 16),
b: parseInt(result[3], 16),
}
: null;
};
//(2017) SIMPLE ES6 composable arrow functions
// https://stackoverflow.com/a/42429333
export const arrayToRGBString = (rgb: number[]): string => `rgb(${rgb.join(',')})`;
export const hexToRGBArray = (hex: string): number[] | undefined =>
hex?.match(/[A-Za-z0-9]{2}/g)?.map((v) => parseInt(v, 16));
export const rgbArrayToHex = (rgb: number[]): string => `#${rgb.map((v) => v.toString(16).padStart(2, '0')).join('')}`;
export const rgbStringToArray = (rgb: string): number[] | undefined =>
rgb
?.match(/^rgb\((\d+),\s*(\d+),\s*(\d+)\)$/)
?.splice(1, 3)
?.map((v) => Number(v));
export const rgbStringToHex = (rgb: string): string | undefined =>
rgb != undefined
? rgbStringToArray(rgb) != undefined
? rgbArrayToHex(rgbStringToArray(rgb) as number[])
: undefined
: undefined;
// https://stackoverflow.com/a/21924155
export const hexToComplementary = (hex: number): string => ('000000' + (0xffffff ^ hex).toString(16)).slice(-6);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment