aboutsummaryrefslogtreecommitdiffhomepage
diff options
context:
space:
mode:
authorAjay Ramachandran <[email protected]>2023-09-05 01:28:23 -0400
committerGitHub <[email protected]>2023-09-05 01:28:23 -0400
commit48cdabe2a5debf45051a9099b0b5ee5ad3c0c8d5 (patch)
tree664d67988b1fe96abc67e9842dd2252aaaa3b9bc
parent843ef37dcd5e5e15f5ace6d36e5c84908048f0ea (diff)
parentbc2db0cf2c13f6e8aac75227694babdf3693d45d (diff)
downloadSponsorBlock-48cdabe2a5debf45051a9099b0b5ee5ad3c0c8d5.tar.gz
SponsorBlock-48cdabe2a5debf45051a9099b0b5ee5ad3c0c8d5.zip
Merge pull request #1534 from EthanBnntt/EthanBnntt-patch-1
Reduced execution time of hexToRgb function by ~70%
-rw-r--r--src/utils/genericUtils.ts27
1 files changed, 12 insertions, 15 deletions
diff --git a/src/utils/genericUtils.ts b/src/utils/genericUtils.ts
index 032539c2..7b7f1118 100644
--- a/src/utils/genericUtils.ts
+++ b/src/utils/genericUtils.ts
@@ -4,20 +4,17 @@ function getLuminance(color: string): number {
return Math.sqrt(0.299 * (r * r) + 0.587 * (g * g) + 0.114 * (b * b));
}
-/* From https://stackoverflow.com/a/5624139 */
-function hexToRgb(hex: string): {r: number; g: number; b: number} {
- // Expand shorthand form (e.g. "03F") to full form (e.g. "0033FF")
- const shorthandRegex = /^#?([a-f\d])([a-f\d])([a-f\d])$/i;
- hex = hex.replace(shorthandRegex, function(m, r, g, b) {
- return 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 ? {
- r: parseInt(result[1], 16),
- g: parseInt(result[2], 16),
- b: parseInt(result[3], 16)
- } : null;
+/* Converts hex color to rgb color */
+const hexChars = "0123456789abcdef";
+function hexToRgb(hex: string): { r: number; g: number; b: number } | null {
+ if (hex.length == 4)
+ hex = "#" + hex[1] + hex[1] + hex[2] + hex[2] + hex[3] + hex[3];
+ 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]),
+ g: hexChars.indexOf(hex[3]) * 16 + hexChars.indexOf(hex[4]),
+ b: hexChars.indexOf(hex[5]) * 16 + hexChars.indexOf(hex[6]),
+ }: null;
}
/**
@@ -31,4 +28,4 @@ function indexesOf<T>(array: T[], value: T): number[] {
export const GenericUtils = {
getLuminance,
indexesOf
-} \ No newline at end of file
+}