UNPKG

material-chalk

Version:

Generate beautiful colors from namespaces based on color theory

55 lines (54 loc) 1.88 kB
"use strict"; /** * Taken from https://github.com/sindresorhus/fnv1a * Inlined to reduce dependencies (given this is a really small piece of code) */ Object.defineProperty(exports, "__esModule", { value: true }); exports.default = fnv1a; const FNV_PRIMES = { 32: 16777619n, }; const FNV_OFFSETS = { 32: 2166136261n, }; const cachedEncoder = new globalThis.TextEncoder(); function fnv1aUint8Array(uint8Array, size) { const fnvPrime = FNV_PRIMES[size]; let hash = FNV_OFFSETS[size]; // eslint-disable-next-line unicorn/no-for-loop -- This is a performance-sensitive loop for (let index = 0; index < uint8Array.length; index++) { hash ^= BigInt(uint8Array[index]); hash = BigInt.asUintN(size, hash * fnvPrime); } return hash; } function fnv1aEncodeInto(string, size, utf8Buffer) { if (utf8Buffer.length === 0) { throw new Error("The `utf8Buffer` option must have a length greater than zero"); } const fnvPrime = FNV_PRIMES[size]; let hash = FNV_OFFSETS[size]; let remaining = string; while (remaining.length > 0) { const result = cachedEncoder.encodeInto(remaining, utf8Buffer); remaining = remaining.slice(result.read); for (let index = 0; index < result.written; index++) { hash ^= BigInt(utf8Buffer[index]); hash = BigInt.asUintN(size, hash * fnvPrime); } } return hash; } function fnv1a(value, options = {}) { const { size = 32, utf8Buffer } = options; if (!FNV_PRIMES[size]) { throw new Error("The `size` option must be one of 32, 64, 128, 256, 512, or 1024"); } if (typeof value === "string") { if (utf8Buffer) { return fnv1aEncodeInto(value, size, utf8Buffer); } return fnv1aUint8Array(cachedEncoder.encode(value), size); } return fnv1aUint8Array(value, size); }