Skip to content

Instantly share code, notes, and snippets.

@SergProduction
Last active September 10, 2023 17:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save SergProduction/836d75a6e05533ab0afbccab0f54aee4 to your computer and use it in GitHub Desktop.
Save SergProduction/836d75a6e05533ab0afbccab0f54aee4 to your computer and use it in GitHub Desktop.
colors util
export type RGBA = [number, number, number, number | undefined]
export const splitStringChunk = (string: string, size: number): string[] => {
const re = new RegExp(".{1," + size + "}", "g")
const maybeResult = string.match(re)
return maybeResult ? maybeResult : []
}
export const hexToRGB = (hex: string): RGBA => {
if (hex.length !== 3 && hex.length !== 6 && hex.length !== 8) {
throw new Error("hex цвет не валидный")
}
const [R, G, B, maybeA] =
hex.length === 3
? hex.split("").map((x) => parseInt(x.repeat(2), 16))
: splitStringChunk(hex, 2).map((x) => parseInt(x, 16))
return [R, G, B, maybeA]
}
export const parseRBGa = (RBGa: string): RGBA => {
const resultParse = RBGa.match(/[\d\.]+/g)
if (resultParse === null || resultParse.length < 3) {
throw new Error("RBGa цвет не валидный")
}
const alphaIsNotDecimal = /%/.test(RBGa)
const [R, G, B, maybeA] = resultParse
let A: number | undefined
if (alphaIsNotDecimal) {
A = parseFloat(`.${maybeA}`)
} else if (maybeA) {
A = parseFloat(maybeA)
}
return [parseInt(R), parseInt(G), parseInt(B), A]
}
export const RGBToHax = (RBGa: string): string => {
const [R, G, B, maybeA] = parseRBGa(RBGa)
let hex = R.toString(16) + G.toString(16) + B.toString(16)
if (maybeA) {
hex += (maybeA * 255).toString(16)
}
return hex
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment