@storm-stack/unique-identifier
Version:
This package provides a simple way to generate various types of unique identifiers.
32 lines (31 loc) • 1.4 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.cuid = cuid;
var _hashing = require("@storm-stack/hashing");
var _random = require("./random.cjs");
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 (0, _hashing.hash)(sourceString).slice(0, Math.max(0, CUID_LARGE_LENGTH));
}
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 = (0, _hashing.hash)(`${time + salt + count + fingerprint()}`);
return `${(0, _random.randomLetter)() + hashed.slice(1, Math.min(hashed.length - 1, CUID_LARGE_LENGTH))}`;
}