UNPKG

keystamp

Version:

A tiny, fast, and collision-resistant unique ID generator for JavaScript, React.js, Node.js, and Express.js, inspired by MiniQid.

71 lines (59 loc) 1.71 kB
const keystamp = (() => { const usedIds = new Set(); const getCharset = (type, customCharset) => { const charsets = { alphanumeric: "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789", numeric: "0123456789", hex: "0123456789abcdef", lowercase: "abcdefghijklmnopqrstuvwxyz", uppercase: "ABCDEFGHIJKLMNOPQRSTUVWXYZ", symbols: '!@#$%^&*()-_=+[]{}|;:,.<>?/`~"₹', binary: "01", custom: customCharset || "", }; if (type === "custom") { if (customCharset.length === 1) { return "0123456789abcdef"; } else { return charsets.custom; } } if (charsets.hasOwnProperty(type)) { return charsets[type]; } if (type.includes("+")) { return type .split("+") .map((t) => charsets[t] || "") .join(""); } return charsets.hex; }; return function generateUniqueId({ prefix = "", suffix = "", length = 24, type = "hex", customCharset = "", } = {}) { const charset = getCharset(type, customCharset); if (!charset || charset.length === 0) { throw new Error('Charset is empty. Check "type" or "customCharset".'); } const generateRandomPart = () => { let str = ""; for (let i = 0; i < length; i++) { str += charset.charAt(Math.floor(Math.random() * charset.length)); } return str; }; let baseId = ""; do { baseId = generateRandomPart(); } while (usedIds.has(baseId)); usedIds.add(baseId); return `${prefix}${baseId}${suffix}`; }; })(); module.exports = keystamp;