Merge pull request #1534 from EthanBnntt/EthanBnntt-patch-1

Reduced execution time of hexToRgb function by ~70%
This commit is contained in:
Ajay Ramachandran
2023-09-05 01:28:23 -04:00
committed by GitHub

View File

@@ -4,20 +4,17 @@ function getLuminance(color: string): number {
return Math.sqrt(0.299 * (r * r) + 0.587 * (g * g) + 0.114 * (b * b)); return Math.sqrt(0.299 * (r * r) + 0.587 * (g * g) + 0.114 * (b * b));
} }
/* From https://stackoverflow.com/a/5624139 */ /* Converts hex color to rgb color */
function hexToRgb(hex: string): {r: number; g: number; b: number} { const hexChars = "0123456789abcdef";
// Expand shorthand form (e.g. "03F") to full form (e.g. "0033FF") function hexToRgb(hex: string): { r: number; g: number; b: number } | null {
const shorthandRegex = /^#?([a-f\d])([a-f\d])([a-f\d])$/i; if (hex.length == 4)
hex = hex.replace(shorthandRegex, function(m, r, g, b) { hex = "#" + hex[1] + hex[1] + hex[2] + hex[2] + hex[3] + hex[3];
return r + r + g + g + b + b; return /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex)
}); ? {
r: hexChars.indexOf(hex[1]) * 16 + hexChars.indexOf(hex[2]),
const result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex); g: hexChars.indexOf(hex[3]) * 16 + hexChars.indexOf(hex[4]),
return result ? { b: hexChars.indexOf(hex[5]) * 16 + hexChars.indexOf(hex[6]),
r: parseInt(result[1], 16), }: null;
g: parseInt(result[2], 16),
b: parseInt(result[3], 16)
} : null;
} }
/** /**
@@ -31,4 +28,4 @@ function indexesOf<T>(array: T[], value: T): number[] {
export const GenericUtils = { export const GenericUtils = {
getLuminance, getLuminance,
indexesOf indexesOf
} }