2018-11-04 06:22:46 +00:00
|
|
|
/* eslint-disable no-bitwise */
|
2018-10-07 23:34:53 +00:00
|
|
|
import { hsluvToHex } from 'hsluv';
|
2018-10-06 22:25:56 +00:00
|
|
|
|
2018-11-04 06:22:46 +00:00
|
|
|
//
|
|
|
|
// github.com/sindresorhus/fnv1a
|
|
|
|
//
|
|
|
|
const OFFSET_BASIS_32 = 2166136261;
|
|
|
|
|
|
|
|
const fnv1a = string => {
|
|
|
|
let hash = OFFSET_BASIS_32;
|
|
|
|
|
|
|
|
for (let i = 0; i < string.length; i++) {
|
|
|
|
hash ^= string.charCodeAt(i);
|
|
|
|
|
|
|
|
// 32-bit FNV prime: 2**24 + 2**8 + 0x93 = 16777619
|
|
|
|
// Using bitshift for accuracy and performance. Numbers in JS suck.
|
|
|
|
hash +=
|
|
|
|
(hash << 1) + (hash << 4) + (hash << 7) + (hash << 8) + (hash << 24);
|
|
|
|
}
|
|
|
|
|
|
|
|
return hash >>> 0;
|
|
|
|
};
|
|
|
|
|
2018-10-06 22:25:56 +00:00
|
|
|
const colors = [];
|
|
|
|
|
|
|
|
for (let i = 0; i < 72; i++) {
|
2018-10-07 23:34:53 +00:00
|
|
|
colors[i] = hsluvToHex([i * 5, 40, 50]);
|
|
|
|
colors[i + 72] = hsluvToHex([i * 5, 70, 50]);
|
|
|
|
colors[i + 144] = hsluvToHex([i * 5, 100, 50]);
|
2018-10-06 22:25:56 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
const cache = {};
|
|
|
|
|
2018-10-07 23:34:53 +00:00
|
|
|
export default function stringToRGB(str) {
|
2018-10-06 22:25:56 +00:00
|
|
|
if (cache[str]) {
|
|
|
|
return cache[str];
|
|
|
|
}
|
|
|
|
|
2018-10-07 23:34:53 +00:00
|
|
|
const color = colors[fnv1a(str) % colors.length];
|
2018-10-06 22:25:56 +00:00
|
|
|
cache[str] = color;
|
|
|
|
return color;
|
|
|
|
}
|