Skip to content

Commit 47f1608

Browse files
committed
Implement hex to rgb utility function
1 parent 19497e8 commit 47f1608

File tree

2 files changed

+25
-2
lines changed

2 files changed

+25
-2
lines changed

pages/index.tsx

Lines changed: 9 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,13 @@
22
import styles from "../styles/Home.module.scss"
33

44
import React, { useEffect, useState } from "react"
5-
import { changeBarsColor, generateBarHeights, getAllBars, startAnimation } from "../utils"
5+
import {
6+
changeBarsColor,
7+
generateBarHeights,
8+
getAllBars,
9+
hexToRgb,
10+
startAnimation,
11+
} from "../utils"
612
import {
713
AppTitle,
814
AlgorithmSelector,
@@ -56,7 +62,8 @@ const Home: React.FC = () => {
5662
setSortingState("Sort")
5763
requestAnimationFrame(() => {
5864
const barsDomEl = getAllBars()
59-
if (barsDomEl[5].style.backgroundColor === "rgb(0, 0, 0)") {
65+
const sampleBg = barsDomEl[5].style.backgroundColor
66+
if (sampleBg === hexToRgb(palette.active)) {
6067
changeBarsColor(barsDomEl, palette.inactive)
6168
}
6269
})

utils/index.ts

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -108,3 +108,19 @@ export const startAnimation = (params: StartAnimationParams) => {
108108
break
109109
}
110110
}
111+
112+
export const hexToRgb = (hex: string) => {
113+
const shorthandRegex = /^#?([a-f\d])([a-f\d])([a-f\d])$/i
114+
hex = hex.replace(shorthandRegex, function (m, r, g, b) {
115+
return r + r + g + g + b + b
116+
})
117+
118+
var result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex)
119+
const rgb = {
120+
r: parseInt(result[1], 16),
121+
g: parseInt(result[2], 16),
122+
b: parseInt(result[3], 16),
123+
}
124+
125+
return result ? `rgb(${rgb.r}, ${rgb.g}, ${rgb.b})` : null
126+
}

0 commit comments

Comments
 (0)