@storm-stack/unique-identifier
Version:
This package provides a simple way to generate various types of unique identifiers.
29 lines (28 loc) • 1.28 kB
JavaScript
import { hash } from "@storm-stack/hashing";
import { randomLetter } from "./random.mjs";
const INITIAL_COUNT_MAX = 476782367;
const CUID_LARGE_LENGTH = 36;
const sequence = 1;
const counter = Math.floor(Math.random() * INITIAL_COUNT_MAX) + sequence;
function createEntropy(length = 4, random = Math.random) {
let entropy = "";
while (entropy.length < length) {
entropy += Math.floor(random() * CUID_LARGE_LENGTH).toString(
CUID_LARGE_LENGTH
);
}
return entropy;
}
function fingerprint(options) {
const globalObj = options?.globalObj ?? typeof global === "undefined" ? typeof window === "undefined" ? {} : window : global;
const globals = Object.keys(globalObj).toString();
const sourceString = globals.length > 0 ? globals + createEntropy(CUID_LARGE_LENGTH, Math.random) : createEntropy(CUID_LARGE_LENGTH, Math.random);
return hash(sourceString).slice(0, Math.max(0, CUID_LARGE_LENGTH));
}
export function cuid() {
const time = Date.now().toString(CUID_LARGE_LENGTH);
const count = counter.toString(CUID_LARGE_LENGTH);
const salt = createEntropy(CUID_LARGE_LENGTH, Math.random);
const hashed = hash(`${time + salt + count + fingerprint()}`);
return `${randomLetter() + hashed.slice(1, Math.min(hashed.length - 1, CUID_LARGE_LENGTH))}`;
}