Created
April 1, 2022 09:13
-
-
Save attitude/3ff9c890da967146d9b58af5c0c47f1a to your computer and use it in GitHub Desktop.
Parses RGB string and returns tuple [R: number, G: number, B: number]
This file contains hidden or 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
const RGB_VALUES_REGEX = new RegExp(/(rgba?)\((.+)\)/) | |
function parseRGBStrict(color: string): [number, number, number] | [number, number, number, number] { | |
const matches = color.match(RGB_VALUES_REGEX) | |
if (!matches) { | |
throw new Error("No RGB color string"); | |
} | |
const scheme = matches[1] | |
if (scheme !== 'rgb' && scheme !== 'rgba') { | |
throw new Error("Not RGB or RGBA color definition"); | |
} | |
const [r, g, b, a, ...rest] = matches[2].split(',') | |
.map(v => v.trim()) | |
.map((rgb, index) => index < 3 && rgb.indexOf('.') < 0 ? parseInt(rgb) : parseFloat(rgb)) | |
if (typeof a === 'number' && scheme !== 'rgba') { | |
throw new Error("RGB string expects 3 values"); | |
} | |
if (typeof a !== 'number' && scheme === 'rgba') { | |
throw new Error("RGBA string expects 4 values"); | |
} | |
if (rest.length !== 0) { | |
throw new Error("Unexpected number of RGB/RGBA channels"); | |
} | |
return typeof a === 'number' ? [r, g, b, a] : [r, g, b] | |
} | |
function parseRGB(color: string): [number, number, number] | [number, number, number, number] | null { | |
try { parseRGBStrict(color) } catch (error) {} | |
return null | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment