random-color-library
Version:
Generate random colors from the Material Design color palette.
47 lines (46 loc) • 1.36 kB
JavaScript
export function randomIntFromHash(key, max) {
const hash = murmur3_32(key);
return hash % max;
}
export function getRandomInt(max) {
return Math.floor(Math.random() * max);
}
export function murmur3_32(key) {
const c1 = 0xcc9e2d51;
const c2 = 0x1b873593;
const r1 = 15;
const r2 = 13;
const m = 5;
const n = 0xe6546b64;
let hash = 0;
const bytes = new TextEncoder().encode(key);
const dataView = new DataView(bytes.buffer);
const chunks = Math.floor(bytes.length / 4);
for (let i = 0; i < chunks; i++) {
let k = dataView.getUint32(i * 4, true);
k = Math.imul(k, c1);
k = (k << r1) | (k >>> (32 - r1));
k = Math.imul(k, c2);
hash ^= k;
hash = (hash << r2) | (hash >>> (32 - r2));
hash = Math.imul(hash, m) + n;
}
const remainder = bytes.length % 4;
if (remainder) {
let k = 0;
for (let i = 0; i < remainder; i++) {
k |= (bytes[chunks * 4 + i] || 0) << (i * 8);
}
k = Math.imul(k, c1);
k = (k << r1) | (k >>> (32 - r1));
k = Math.imul(k, c2);
hash ^= k;
}
hash ^= bytes.length;
hash ^= hash >>> 16;
hash = Math.imul(hash, 0x85ebca6b);
hash ^= hash >>> 13;
hash = Math.imul(hash, 0xc2b2ae35);
hash ^= hash >>> 16;
return hash >>> 0;
}