UNPKG

@cstan/local-uid

Version:

A CommonJS module that generates and tests for a unique identifier.

36 lines (35 loc) 1.11 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.isValidLuid = exports.createLuid = void 0; const { onlyDigits } = require("@cstan/only-digits"); const rand = () => { return (Math.floor(Math.random() * (65535 - 4096 + 1)) + 4096).toString(16); }; const me = (s) => { let hash = ""; let i = 0; const sn = s + "j8cls3$w"; while (hash.length < 8) { hash += (sn.charCodeAt(i) & 15).toString(16); i += 1; } return hash; }; // This creates a unique id that passes the isValidLuid() test // is compatible with established projects legacy unique id. function createLuid(seed = "") { const d = Number(onlyDigits(new Date().toISOString())) .toString(16) .slice(-12); let luid_array = []; luid_array.push(d); luid_array.push(me(seed)); luid_array.push(rand()); luid_array.push(rand()); return luid_array.join("-"); } exports.createLuid = createLuid; function isValidLuid(id) { return /^[0-9a-fA-F]{12}-[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}$/.test(id); } exports.isValidLuid = isValidLuid;