Skip to content

Instantly share code, notes, and snippets.

@willmendesneto
Last active May 17, 2020 15:02
Show Gist options
  • Save willmendesneto/33a8742a7287de72babf658ccceeb0ec to your computer and use it in GitHub Desktop.
Save willmendesneto/33a8742a7287de72babf658ccceeb0ec to your computer and use it in GitHub Desktop.
Check if color is lighter or darker. Remove the comments and you can use the power of types (optional)
// This file is Typescript friendly
// Which means you can replace the function signatures and get
// the power of types in your WebApp 🔋
// const hexToRgb = (colorinHex: string): [number, number, number] | [] => {
const hexToRgb = (colorinHex) => {
// Expand shorthand form (e.g. "03F") to full form (e.g. "0033FF")
const expandShorthandHexToFullForm = /^#?([a-f\d])([a-f\d])([a-f\d])$/i;
const hex = colorinHex.replace(expandShorthandHexToFullForm, (m, r, g, b) => r + r + g + g + b + b);
const result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);
return result ? [parseInt(result[1], 16), parseInt(result[2], 16), parseInt(result[3], 16)] : [];
};
// export const isLight(colorinHex: string): boolean {
export const isLight(colorinHex) {
const [red, green, blue] = hexToRgb(colorinHex);
// Displaying an error in case something goes wrong during tranformation
if (!red || !green || !blue) {
throw new Error(`Unable to transform ${colorinHex} to hex.`);
}
const brightness = (red * 299 + green * 587 + blue * 114) / 1000;
// If it's not light, that means it's dark
return brightness > 128;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment