parseRGB = (() => {
const fractional = ["(?:[.]0*)?", "(?:[.]\\d*)?"];
const percentage =
"(?:100" + fractional[0] + "|[1-9]?\\d?" + fractional[1] + ")%";
const isRGB = new RegExp(
[
"^rgba?\\(",
["R", "G", "B"]
.map(
(C) =>
["(?<", C, ">"].join("") +
[
"none",
"(?:255" +
fractional[0] +
"|(?:25[0-4]|2[0-4]\\d|1\\d{1,2}|[1-9]?\\d?)" +
fractional[1] +
")",
percentage
].join("|") +
")"
)
.join("(?:\\s*,\\s*|\\s+)"),
"(?:\\s*[,\\/]\\s*",
"(?<A>" +
[
"none",
"(?:1" + fractional[0] + "|0?" + fractional[1] + ")",
percentage
].join("|") +
")",
")?",
"\\)$"
].join(""),
"i"
);
return (rgba = "") => {
try {
const components = rgba
.trim()
.match(isRGB)
.slice(1)
.map((x, i) =>
["none", ".", ".%"].includes(x)
? i < 3
? 0
: [0, NaN][+(x === "none")]
: (
parseFloat(x, 10) /
((x || "").match(/%$/)
? 100
: i < 3
? 255
: 1)
).toFixed(6) * 1
);
return components;
} catch (e) {
throw Error("Argument is not a sRGB color");
}
};
})()