nhb-toolbox
Version:
A versatile collection of smart, efficient, and reusable utility functions, classes and types for everyday development needs.
43 lines (42 loc) • 1.75 kB
JavaScript
import { isNumber, isString } from '../guards/primitives.js';
import { ALPHABET_COLOR_PALETTE, NUMBER_COLOR_PALETTE } from './constants.js';
import { _applyOpacity } from './helpers.js';
import { percentToHex } from './utils.js';
export function getColorForInitial(input = '', opacity = 100) {
let initial;
const hexOpacity = percentToHex(opacity);
const NUMBERS = '0123456789';
const DEFAULT = '#010514';
if (!input)
return _applyOpacity(DEFAULT, hexOpacity);
if (isString(input)) {
initial = input[0];
if (NUMBERS.includes(initial)) {
return _applyOpacity(NUMBER_COLOR_PALETTE[parseInt(initial, 10)], hexOpacity);
}
const upperInitial = initial.toUpperCase();
const index = upperInitial.charCodeAt(0) - 'A'.charCodeAt(0);
if (index >= 0 && index < ALPHABET_COLOR_PALETTE?.length) {
return _applyOpacity(ALPHABET_COLOR_PALETTE[index], hexOpacity);
}
return _applyOpacity(DEFAULT, hexOpacity);
}
else if (isNumber(input)) {
initial = input.toString()[0];
if (NUMBERS.includes(initial)) {
return _applyOpacity(NUMBER_COLOR_PALETTE[parseInt(initial, 10)], hexOpacity);
}
return _applyOpacity(DEFAULT, hexOpacity);
}
else if (Array.isArray(input)) {
if (input?.length < 1)
return [...ALPHABET_COLOR_PALETTE, ...NUMBER_COLOR_PALETTE].map((color) => _applyOpacity(color, hexOpacity));
return input.flatMap((el) => {
if (Array.isArray(el)) {
return getColorForInitial(el, opacity);
}
return getColorForInitial(el, opacity);
});
}
return _applyOpacity(DEFAULT, hexOpacity);
}