Skip to content

Instantly share code, notes, and snippets.

@attitude
Created April 1, 2022 09:13
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 attitude/3ff9c890da967146d9b58af5c0c47f1a to your computer and use it in GitHub Desktop.
Save attitude/3ff9c890da967146d9b58af5c0c47f1a to your computer and use it in GitHub Desktop.
Parses RGB string and returns tuple [R: number, G: number, B: number]
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