Skip to content

Instantly share code, notes, and snippets.

@ozgurg
Created June 11, 2024 23:59
Show Gist options
  • Save ozgurg/ef017c9e808dd58c3808ee4823cd3e21 to your computer and use it in GitHub Desktop.
Save ozgurg/ef017c9e808dd58c3808ee4823cd3e21 to your computer and use it in GitHub Desktop.
JS StringToColorConverter (Ported with minor adjustments by ChatGTP 4o from https://github.com/shahonseven/php-color-hash)
class StringToColorConverter {
static L = [
0.35,
0.5,
0.65
];
static S = [
0.35,
0.5,
0.65
];
static getCharCode(c) {
return c.codePointAt(0);
}
static hash(string) {
const seed = 131;
const seed2 = 137;
let hash = 0;
string += "x";
const max = 9007199254740991 / seed2;
for (let i = 0; i < string.length; i++) {
if (hash > max) {
hash = Math.floor(hash / seed2);
}
hash = hash * seed + this.getCharCode(string[i]);
}
return hash;
}
static rgbToHex([r, g, b]) {
return `#${((1 << 24) + (r << 16) + (g << 8) + b).toString(16).slice(1)}`;
}
static hslToRgb(h, s, l) {
h /= 360;
const q = l < 0.5 ? l * (1 + s) : l + s - l * s;
const p = 2 * l - q;
const hueToRgb = (p, q, t) => {
if (t < 0) t += 1;
if (t > 1) t -= 1;
if (t < 1 / 6) return p + (q - p) * 6 * t;
if (t < 0.5) return q;
if (t < 2 / 3) return p + (q - p) * (2 / 3 - t) * 6;
return p;
};
return [
Math.round(hueToRgb(p, q, h + 1 / 3) * 255),
Math.round(hueToRgb(p, q, h) * 255),
Math.round(hueToRgb(p, q, h - 1 / 3) * 255)
];
}
static stringToHsl(string) {
let hash = this.hash(string);
const hue = hash % 359;
hash = Math.floor(hash / 360);
const saturation = this.S[hash % this.S.length];
hash = Math.floor(hash / this.S.length);
const lightness = this.L[hash % this.L.length];
return {
hue,
saturation,
lightness
};
}
static stringToRgb(string) {
const {
hue,
saturation,
lightness
} = this.stringToHsl(string);
return this.hslToRgb(hue, saturation, lightness);
}
static stringToHex(string) {
return this.rgbToHex(this.stringToRgb(string));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment