random-color-library
Version:
Generate random colors from the Material Design color palette.
59 lines (58 loc) • 2.29 kB
JavaScript
import { listOfColors, listOfShades, materialColors, } from "./materialColors.js";
import { getRandomInt, randomIntFromHash } from "./utils.js";
function isListOfShades(value) {
return listOfShades.includes(value);
}
function isListOfColors(value) {
return listOfColors.includes(value);
}
export function randomMaterialColor(arg1, arg2) {
const options = typeof arg1 === "object" ? arg1 : typeof arg2 === "object" ? arg2 : {};
const text = typeof arg1 === "string" ? arg1 : undefined;
if (Object.keys(options).some((key) => !["colors", "shades", "excludeColors", "excludeShades"].includes(key))) {
throw new Error("Invalid option provided");
}
if (options.colors && options.excludeColors) {
throw new Error("Cannot provide both colors and excludeColors");
}
if (options.shades && options.excludeShades) {
throw new Error("Cannot provide both shades and excludeShades");
}
if (options.colors && !options.colors.every(isListOfColors)) {
throw new Error("Invalid color provided");
}
if (options.shades && !options.shades.every(isListOfShades)) {
throw new Error("Invalid shade provided");
}
if (options.excludeColors && !options.excludeColors.every(isListOfColors)) {
throw new Error("Invalid color provided");
}
if (options.excludeShades && !options.excludeShades.every(isListOfShades)) {
throw new Error("Invalid shade provided");
}
let colors = options?.colors || listOfColors;
let shades = options?.shades || listOfShades;
let color;
let shade;
if (options.excludeShades) {
shades = shades.filter((shade) => !options.excludeShades?.includes(shade));
}
if (options.excludeColors) {
colors = colors.filter((color) => !options.excludeColors?.includes(color));
}
if (!text) {
color = colors[getRandomInt(colors.length)];
shade = shades[getRandomInt(shades.length)];
}
else {
color = colors[randomIntFromHash(text, colors.length)];
shade = shades[randomIntFromHash(text, shades.length)];
}
if (!color) {
throw new Error("No color found");
}
if (!shade) {
throw new Error("No shade found");
}
return materialColors?.[color]?.[shade];
}