nhb-toolbox
Version:
A versatile collection of smart, efficient, and reusable utility functions and classes for everyday development needs.
43 lines (42 loc) • 1.78 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.generateRandomColorInHexRGB = exports.generateRandomHSLColor = void 0;
const convert_1 = require("./convert");
const helpers_1 = require("./helpers");
/** Track previously generated colors. */
const generatedColors = new Set();
/** Array of recently generated colors */
const recentColors = [];
/**
* * Utility to generate a unique random HSL color.
*
* @param maxColors - The maximum number of recent colors to store in memory. Default is `16`.
* @returns Generated unique random color in `HSL` format.
*/
const generateRandomHSLColor = (maxColors = 16) => {
let color;
// Keep generating until a unique color is found that is also different from the last one
do {
color = (0, helpers_1._generateRandomHSL)();
} while (generatedColors.has(color) ||
(0, helpers_1._isSimilarToLast)(recentColors, color));
// Add the newly generated color to the set and recent colors
generatedColors.add(color);
recentColors.push(color);
// Limit the recent colors to the last `maxColors` to avoid excessive memory usage
if (recentColors?.length > maxColors) {
recentColors?.shift();
}
return color;
};
exports.generateRandomHSLColor = generateRandomHSLColor;
/**
* * Utility to generate a unique random color in Hex and RGB format.
*
* @param maxColors - The maximum number of recent colors to store in memory. Default is `16`.
* @returns An object of generated unique random color in both `Hex` and `RGB` formats.
*/
const generateRandomColorInHexRGB = (maxColors = 16) => {
return (0, convert_1.convertColorCode)((0, exports.generateRandomHSLColor)(maxColors));
};
exports.generateRandomColorInHexRGB = generateRandomColorInHexRGB;