Last active
September 10, 2023 17:36
-
-
Save SergProduction/836d75a6e05533ab0afbccab0f54aee4 to your computer and use it in GitHub Desktop.
colors util
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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