diff --git a/dist/short-unique-id.js b/dist/short-unique-id.js index e3bf50a..2fa4a86 100644 --- a/dist/short-unique-id.js +++ b/dist/short-unique-id.js @@ -45,7 +45,7 @@ var ShortUniqueId = (() => { }); // package.json - var version = "5.1.1"; + var version = "5.2.0"; // src/index.ts var DEFAULT_UUID_LENGTH = 6; diff --git a/dist/short-unique-id.js.map b/dist/short-unique-id.js.map index 84bd9ec..42d184e 100644 --- a/dist/short-unique-id.js.map +++ b/dist/short-unique-id.js.map @@ -1,7 +1,7 @@ { "version": 3, "sources": ["../src/index.ts", "../package.json"], - "sourcesContent": ["/**\n * @packageDocumentation\n **/\n\n// Copyright 2017-2022 the Short Unique ID authors. All rights reserved. Apache 2.0 license.\n\n// @ts-ignore\nimport {version} from '../package.json';\n\nexport interface ShortUniqueIdRanges {\n [k: string]: [number, number];\n};\n\nexport interface ShortUniqueIdRangesMap {\n [k: string]: ShortUniqueIdRanges;\n};\n\nexport type ShortUniqueIdDefaultDictionaries = 'number' | 'alpha' | 'alpha_lower' | 'alpha_upper' | 'alphanum' | 'alphanum_lower' | 'alphanum_upper' | 'hex';\n\n/**\n * ```js\n * {\n * dictionary: ['z', 'a', 'p', 'h', 'o', 'd', ...],\n * shuffle: false,\n * debug: false,\n * length: 6,\n * }\n * ```\n *
\n * @see {@link DEFAULT_OPTIONS}\n */\nexport interface ShortUniqueIdOptions {\n /** User-defined character dictionary */\n dictionary: string[] | ShortUniqueIdDefaultDictionaries;\n\n /** If true, sequentialUUID use the dictionary in the given order */\n shuffle: boolean;\n\n /** If true the instance will console.log useful info */\n debug: boolean;\n\n /** From 1 to infinity, the length you wish your UUID to be */\n length: number;\n\n /** From 0 to infinity, the current value for the sequential UUID counter */\n counter: number;\n};\n\n/**\n * 6 was chosen as the default UUID length since for most cases\n * it will be more than aptly suitable to provide millions of UUIDs\n * with a very low probability of producing a duplicate UUID.\n *\n * For example, with a dictionary including digits from 0 to 9,\n * as well as the alphabet from a to z both in UPPER and lower case,\n * the probability of generating a duplicate in 1,000,000 rounds\n * is ~0.00000002, or about 1 in 50,000,000.\n */\nexport const DEFAULT_UUID_LENGTH: number = 6;\n\nexport const DEFAULT_OPTIONS: ShortUniqueIdOptions = {\n dictionary: 'alphanum',\n shuffle: true,\n debug: false,\n length: DEFAULT_UUID_LENGTH,\n counter: 0,\n};\n\n/**\n * Generate random or sequential UUID of any length.\n *\n * ### Use as module\n *\n * ```js\n * // Deno (web module) Import\n * import ShortUniqueId from 'https://cdn.jsdelivr.net/npm/short-unique-id@latest/src/index.ts';\n *\n * // ES6 / TypeScript Import\n * import ShortUniqueId from 'short-unique-id';\n *\n * // or Node.js require\n * const ShortUniqueId = require('short-unique-id');\n *\n * // Instantiate\n * const uid = new ShortUniqueId();\n *\n * // Random UUID\n * console.log(uid.rnd());\n *\n * // Sequential UUID\n * console.log(uid.seq());\n * ```\n *\n * ### Use in browser\n *\n * ```html\n * \n * \n *\n * \n * \n * ```\n *\n * ### Options\n *\n * Options can be passed when instantiating `uid`:\n *\n * ```js\n * const options = { ... };\n *\n * const uid = new ShortUniqueId(options);\n * ```\n *\n * For more information take a look at the [ShortUniqueIdOptions type definition](/interfaces/shortuniqueidoptions.html).\n */\nexport default class ShortUniqueId {\n /** @hidden */\n static default: typeof ShortUniqueId = ShortUniqueId;\n\n public counter: number;\n public debug: boolean;\n public dict: string[];\n public version: string;\n public dictIndex: number = 0;\n public dictRange: number[] =[];\n public lowerBound: number = 0;\n public upperBound: number = 0;\n public dictLength: number = 0;\n public uuidLength: number;\n\n protected _digit_first_ascii: number = 48;\n protected _digit_last_ascii: number = 58;\n protected _alpha_lower_first_ascii: number = 97;\n protected _alpha_lower_last_ascii: number = 123;\n protected _hex_last_ascii: number = 103;\n protected _alpha_upper_first_ascii: number = 65;\n protected _alpha_upper_last_ascii: number = 91;\n\n protected _number_dict_ranges: ShortUniqueIdRanges = {\n digits: [this._digit_first_ascii, this._digit_last_ascii],\n };\n\n protected _alpha_dict_ranges: ShortUniqueIdRanges = {\n lowerCase: [this._alpha_lower_first_ascii, this._alpha_lower_last_ascii],\n upperCase: [this._alpha_upper_first_ascii, this._alpha_upper_last_ascii],\n };\n\n protected _alpha_lower_dict_ranges: ShortUniqueIdRanges = {\n lowerCase: [this._alpha_lower_first_ascii, this._alpha_lower_last_ascii],\n };\n\n protected _alpha_upper_dict_ranges: ShortUniqueIdRanges = {\n upperCase: [this._alpha_upper_first_ascii, this._alpha_upper_last_ascii],\n };\n\n protected _alphanum_dict_ranges: ShortUniqueIdRanges = {\n digits: [this._digit_first_ascii, this._digit_last_ascii],\n lowerCase: [this._alpha_lower_first_ascii, this._alpha_lower_last_ascii],\n upperCase: [this._alpha_upper_first_ascii, this._alpha_upper_last_ascii],\n };\n\n protected _alphanum_lower_dict_ranges: ShortUniqueIdRanges = {\n digits: [this._digit_first_ascii, this._digit_last_ascii],\n lowerCase: [this._alpha_lower_first_ascii, this._alpha_lower_last_ascii],\n };\n\n protected _alphanum_upper_dict_ranges: ShortUniqueIdRanges = {\n digits: [this._digit_first_ascii, this._digit_last_ascii],\n upperCase: [this._alpha_upper_first_ascii, this._alpha_upper_last_ascii],\n };\n\n protected _hex_dict_ranges: ShortUniqueIdRanges = {\n decDigits: [this._digit_first_ascii, this._digit_last_ascii],\n alphaDigits: [this._alpha_lower_first_ascii, this._hex_last_ascii],\n };\n\n protected _dict_ranges: ShortUniqueIdRangesMap = {\n _number_dict_ranges: this._number_dict_ranges,\n _alpha_dict_ranges: this._alpha_dict_ranges,\n _alpha_lower_dict_ranges: this._alpha_lower_dict_ranges,\n _alpha_upper_dict_ranges: this._alpha_upper_dict_ranges,\n _alphanum_dict_ranges: this._alphanum_dict_ranges,\n _alphanum_lower_dict_ranges: this._alphanum_lower_dict_ranges,\n _alphanum_upper_dict_ranges: this._alphanum_upper_dict_ranges,\n _hex_dict_ranges: this._hex_dict_ranges,\n };\n\n /* tslint:disable consistent-return */\n protected log = (...args: any[]): void => {\n const finalArgs = [...args];\n finalArgs[0] = `[short-unique-id] ${args[0]}`;\n /* tslint:disable no-console */\n if (this.debug === true) {\n if (typeof console !== 'undefined' && console !== null) {\n return console.log(...finalArgs);\n }\n }\n /* tslint:enable no-console */\n };\n /* tslint:enable consistent-return */\n\n protected _normalizeDictionary = (dictionary: string[] | ShortUniqueIdDefaultDictionaries, shuffle?: boolean): string[] => {\n let finalDict: string[];\n\n if (dictionary && Array.isArray(dictionary) && dictionary.length > 1) {\n finalDict = dictionary as string[];\n } else {\n finalDict = [];\n\n let i;\n\n this.dictIndex = i = 0;\n\n const rangesName = `_${dictionary as ShortUniqueIdDefaultDictionaries}_dict_ranges`;\n const ranges = this._dict_ranges[rangesName];\n\n Object.keys(ranges).forEach((rangeType) => {\n const rangeTypeKey = rangeType;\n\n this.dictRange = ranges[rangeTypeKey];\n\n this.lowerBound = this.dictRange[0];\n this.upperBound = this.dictRange[1];\n\n for (\n this.dictIndex = i = this.lowerBound;\n this.lowerBound <= this.upperBound ? i < this.upperBound : i > this.upperBound;\n this.dictIndex = this.lowerBound <= this.upperBound ? i += 1 : i -= 1\n ) {\n finalDict.push(String.fromCharCode(this.dictIndex));\n }\n });\n }\n\n if (shuffle) {\n // Shuffle Dictionary to remove selection bias.\n const PROBABILITY = 0.5;\n finalDict = finalDict.sort(() => Math.random() - PROBABILITY);\n }\n\n return finalDict;\n }\n\n /** Change the dictionary after initialization. */\n setDictionary = (dictionary: string[] | ShortUniqueIdDefaultDictionaries, shuffle?: boolean): void => {\n this.dict = this._normalizeDictionary(dictionary, shuffle);\n\n // Cache Dictionary Length for future usage.\n this.dictLength = this.dict.length;\n\n // Reset internal counter.\n this.setCounter(0);\n };\n\n seq = (): string => {\n return this.sequentialUUID();\n };\n\n /**\n * Generates UUID based on internal counter that's incremented after each ID generation.\n * @alias `const uid = new ShortUniqueId(); uid.seq();`\n */\n sequentialUUID = (): string => {\n let counterDiv: number;\n let counterRem: number;\n let id: string = '';\n\n counterDiv = this.counter;\n\n do {\n counterRem = counterDiv % this.dictLength;\n counterDiv = Math.trunc(counterDiv / this.dictLength);\n id += this.dict[counterRem];\n } while (counterDiv !== 0);\n\n this.counter += 1;\n\n return id;\n };\n\n rnd = (uuidLength: number = this.uuidLength || DEFAULT_UUID_LENGTH): string => {\n return this.randomUUID(uuidLength);\n };\n\n /**\n * Generates UUID by creating each part randomly.\n * @alias `const uid = new ShortUniqueId(); uid.rnd(uuidLength: number);`\n */\n randomUUID = (uuidLength: number = this.uuidLength || DEFAULT_UUID_LENGTH): string => {\n let id: string;\n let randomPartIdx: number;\n let j: number;\n\n if ((uuidLength === null || typeof uuidLength === 'undefined') || uuidLength < 1) {\n throw new Error('Invalid UUID Length Provided');\n }\n\n const isPositive = uuidLength >= 0;\n\n // Generate random ID parts from Dictionary.\n id = '';\n for (\n j = 0;\n j < uuidLength;\n j += 1\n ) {\n randomPartIdx = parseInt(\n (Math.random() * this.dictLength).toFixed(0),\n 10,\n ) % this.dictLength;\n id += this.dict[randomPartIdx];\n }\n\n // Return random generated ID.\n return id;\n };\n\n fmt = (format: string, date?: Date): string => {\n return this.formattedUUID(format, date);\n };\n\n /**\n * Generates custom UUID with the provided format string.\n * @alias `const uid = new ShortUniqueId(); uid.fmt(format: string);`\n */\n formattedUUID = (format: string, date?: Date): string => {\n const fnMap = {\n '$r': this.randomUUID,\n '$s': this.sequentialUUID,\n '$t': this.stamp,\n };\n\n const result = format.replace(\n /\\$[rs]\\d{0,}|\\$t0|\\$t[1-9]\\d{1,}/g,\n (m) => {\n const fn = m.slice(0, 2);\n const len = parseInt(m.slice(2), 10);\n\n if (fn === '$s') {\n return fnMap[fn]().padStart(len, '0');\n }\n\n if (fn === '$t' && date) {\n return fnMap[fn](len, date);\n }\n\n return fnMap[fn as keyof typeof fnMap](len);\n },\n );\n\n return result;\n };\n\n /**\n * Calculates total number of possible UUIDs.\n *\n * Given that:\n *\n * - `H` is the total number of possible UUIDs\n * - `n` is the number of unique characters in the dictionary\n * - `l` is the UUID length\n *\n * Then `H` is defined as `n` to the power of `l`:\n *\n *
\n * \n *
\n *\n * This function returns `H`.\n */\n availableUUIDs = (uuidLength: number = this.uuidLength): number => {\n return parseFloat(\n Math.pow([...new Set(this.dict)].length, uuidLength).toFixed(0),\n );\n };\n\n /**\n * Calculates approximate number of hashes before first collision.\n *\n * Given that:\n *\n * - `H` is the total number of possible UUIDs, or in terms of this library,\n * the result of running `availableUUIDs()`\n * - the expected number of values we have to choose before finding the\n * first collision can be expressed as the quantity `Q(H)`\n *\n * Then `Q(H)` can be approximated as the square root of the product of half\n * of pi times `H`:\n *\n *
\n * \n *
\n *\n * This function returns `Q(H)`.\n * \n * (see [Poisson distribution](https://en.wikipedia.org/wiki/Poisson_distribution))\n */\n approxMaxBeforeCollision = (rounds: number = this.availableUUIDs(this.uuidLength)): number => {\n return parseFloat(\n Math.sqrt((Math.PI / 2) * rounds).toFixed(20),\n );\n };\n\n /**\n * Calculates probability of generating duplicate UUIDs (a collision) in a\n * given number of UUID generation rounds.\n *\n * Given that:\n *\n * - `r` is the maximum number of times that `randomUUID()` will be called,\n * or better said the number of _rounds_\n * - `H` is the total number of possible UUIDs, or in terms of this library,\n * the result of running `availableUUIDs()`\n *\n * Then the probability of collision `p(r; H)` can be approximated as the result\n * of dividing the square root of the product of half of pi times `r` by `H`:\n *\n *
\n * \n *
\n *\n * This function returns `p(r; H)`.\n * \n * (see [Poisson distribution](https://en.wikipedia.org/wiki/Poisson_distribution))\n *\n * (Useful if you are wondering _\"If I use this lib and expect to perform at most\n * `r` rounds of UUID generations, what is the probability that I will hit a duplicate UUID?\"_.)\n */\n collisionProbability = (\n rounds: number = this.availableUUIDs(this.uuidLength),\n uuidLength: number = this.uuidLength,\n ): number => {\n return parseFloat(\n (\n this.approxMaxBeforeCollision(rounds) / this.availableUUIDs(uuidLength)\n ).toFixed(20),\n );\n };\n\n /**\n * Calculate a \"uniqueness\" score (from 0 to 1) of UUIDs based on size of\n * dictionary and chosen UUID length.\n *\n * Given that:\n *\n * - `H` is the total number of possible UUIDs, or in terms of this library,\n * the result of running `availableUUIDs()`\n * - `Q(H)` is the approximate number of hashes before first collision,\n * or in terms of this library, the result of running `approxMaxBeforeCollision()`\n *\n * Then `uniqueness` can be expressed as the additive inverse of the probability of\n * generating a \"word\" I had previously generated (a duplicate) at any given iteration\n * up to the the total number of possible UUIDs expressed as the quotiend of `Q(H)` and `H`:\n *\n *
\n * \n *
\n *\n * (Useful if you need a value to rate the \"quality\" of the combination of given dictionary\n * and UUID length. The closer to 1, higher the uniqueness and thus better the quality.)\n */\n uniqueness = (rounds: number = this.availableUUIDs(this.uuidLength)): number => {\n const score = parseFloat(\n (1 - (\n this.approxMaxBeforeCollision(rounds) / rounds\n )).toFixed(20),\n );\n return (\n score > 1\n ) ? (\n 1\n ) : (\n (score < 0) ? 0 : score\n );\n };\n\n /**\n * Return the version of this module.\n */\n getVersion = (): string => {\n return this.version;\n };\n\n /**\n * Generates a UUID with a timestamp that can be extracted using `uid.parseStamp(stampString);`.\n * \n * ```js\n * const uidWithTimestamp = uid.stamp(32);\n * console.log(uidWithTimestamp);\n * // GDa608f973aRCHLXQYPTbKDbjDeVsSb3\n * \n * console.log(uid.parseStamp(uidWithTimestamp));\n * // 2021-05-03T06:24:58.000Z\n * ```\n */\n stamp = (finalLength: number, date?: Date): string => {\n const hexStamp = Math.floor(+(date || new Date()) / 1000).toString(16);\n\n if (typeof finalLength === 'number' && finalLength === 0) {\n return hexStamp;\n }\n\n if (typeof finalLength !== 'number' || finalLength < 10) {\n throw new Error(\n [\n 'Param finalLength must be a number greater than or equal to 10,',\n 'or 0 if you want the raw hexadecimal timestamp',\n ].join('\\n')\n );\n }\n\n const idLength = finalLength - 9;\n\n const rndIdx = Math.round(Math.random() * ((idLength > 15) ? 15 : idLength));\n\n const id = this.randomUUID(idLength);\n\n return `${id.substring(0, rndIdx)}${hexStamp}${id.substring(rndIdx)}${rndIdx.toString(16)}`;\n };\n\n /**\n * Extracts the date embeded in a UUID generated using the `uid.stamp(finalLength);` method.\n * \n * ```js\n * const uidWithTimestamp = uid.stamp(32);\n * console.log(uidWithTimestamp);\n * // GDa608f973aRCHLXQYPTbKDbjDeVsSb3\n * \n * console.log(uid.parseStamp(uidWithTimestamp));\n * // 2021-05-03T06:24:58.000Z\n * ```\n */\n parseStamp = (suid: string, format?: string): Date => {\n if (format && !(/t0|t[1-9]\\d{1,}/).test(format)) {\n throw new Error('Cannot extract date from a formated UUID with no timestamp in the format');\n }\n\n const stamp = (\n format\n ) ? (\n format.replace(\n /\\$[rs]\\d{0,}|\\$t0|\\$t[1-9]\\d{1,}/g,\n (m) => {\n const fnMap = {\n '$r': (len: number) => [...Array(len)].map(() => 'r').join(''),\n '$s': (len: number) => [...Array(len)].map(() => 's').join(''),\n '$t': (len: number) => [...Array(len)].map(() => 't').join(''),\n };\n\n const fn = m.slice(0, 2);\n const len = parseInt(m.slice(2), 10);\n\n return fnMap[fn as keyof typeof fnMap](len);\n },\n ).replace(\n /^(.*?)(t{8,})(.*)$/g,\n (_m, p1, p2) => {\n return suid.substring(p1.length, p1.length + p2.length);\n },\n )\n ) : (\n suid\n );\n\n if (stamp.length === 8) {\n return new Date(parseInt(stamp, 16) * 1000);\n }\n\n if (stamp.length < 10) {\n throw new Error('Stamp length invalid');\n }\n\n const rndIdx = parseInt(stamp.substring(stamp.length - 1), 16);\n\n return new Date(parseInt(stamp.substring(rndIdx, rndIdx + 8), 16) * 1000);\n };\n\n /**\n * Set the counter to a specific value.\n */\n setCounter = (counter: number): void => {\n this.counter = counter;\n };\n\n /**\n * Validate given UID contains only characters from the instanced dictionary or optionally provided dictionary.\n */\n validate = (uid: string, dictionary?: string[] | ShortUniqueIdDefaultDictionaries): boolean => {\n const finalDictionary = dictionary ? this._normalizeDictionary(dictionary) : this.dict;\n\n return uid.split('').every((c) => finalDictionary.includes(c));\n };\n\n constructor(argOptions: Partial = {}) {\n const options: ShortUniqueIdOptions = {\n ...DEFAULT_OPTIONS,\n ...argOptions as Partial,\n };\n\n this.counter = 0;\n this.debug = false;\n this.dict = [];\n this.version = version;\n\n const {\n dictionary,\n shuffle,\n length,\n counter,\n } = options;\n\n this.uuidLength = length;\n\n this.setDictionary(dictionary, shuffle);\n this.setCounter(counter);\n\n this.debug = options.debug;\n this.log(this.dict);\n this.log(\n `Generator instantiated with Dictionary Size ${this.dictLength} and counter set to ${this.counter}`\n );\n\n this.log = this.log.bind(this);\n this.setDictionary = this.setDictionary.bind(this);\n this.setCounter = this.setCounter.bind(this);\n this.seq = this.seq.bind(this);\n this.sequentialUUID = this.sequentialUUID.bind(this);\n this.rnd = this.rnd.bind(this);\n this.randomUUID = this.randomUUID.bind(this);\n this.fmt = this.fmt.bind(this);\n this.formattedUUID = this.formattedUUID.bind(this);\n this.availableUUIDs = this.availableUUIDs.bind(this);\n this.approxMaxBeforeCollision = this.approxMaxBeforeCollision.bind(this);\n this.collisionProbability = this.collisionProbability.bind(this);\n this.uniqueness = this.uniqueness.bind(this);\n this.getVersion = this.getVersion.bind(this);\n this.stamp = this.stamp.bind(this);\n this.parseStamp = this.parseStamp.bind(this);\n\n return this;\n }\n}\n", "{\n \"name\": \"short-unique-id\",\n \"version\": \"5.1.1\",\n \"description\": \"Generate random or sequential UUID of any length\",\n \"keywords\": [\n \"short\",\n \"random\",\n \"uid\",\n \"uuid\",\n \"guid\",\n \"node\",\n \"unique id\",\n \"generator\",\n \"tiny\"\n ],\n \"bin\": {\n \"short-unique-id\": \"bin/short-unique-id\",\n \"suid\": \"bin/short-unique-id\"\n },\n \"main\": \"dist/short-unique-id.js\",\n \"types\": \"dist/short-unique-id.d.ts\",\n \"homepage\": \"https://shortunique.id\",\n \"repository\": {\n \"type\": \"git\",\n \"url\": \"https://github.com/jeanlescure/short-unique-id\"\n },\n \"license\": \"Apache-2.0\",\n \"runkitExampleFilename\": \"./runkit.js\",\n \"scripts\": {\n \"test\": \"tsx ./src/test.ts\",\n \"test:local\": \"tsx ./src/test.ts && tsx --tsconfig ./specs/esm/tsconfig.json ./specs/esm/import.spec.ts && ./scripts/cjs-test\",\n \"build\": \"./scripts/build\",\n \"docs\": \"./scripts/docs\",\n \"release\": \"release-it\"\n },\n \"release-it\": {\n \"git\": {\n \"changelog\": \"auto-changelog --stdout -l false -u -t ./assets/changelog-compact.hbs\"\n },\n \"hooks\": {\n \"after:bump\": \"./scripts/release\"\n },\n \"npm\": {\n \"publish\": false\n }\n },\n \"files\": [\n \"bin\",\n \"dist\",\n \"runkit.js\",\n \"package.json\"\n ],\n \"devDependencies\": {\n \"@types/node\": \"^20.12.7\",\n \"auto-changelog\": \"^2.4.0\",\n \"esbuild\": \"^0.18.10\",\n \"refup\": \"^1.1.0\",\n \"release-it\": \"^15.11.0\",\n \"tslib\": \"^2.6.2\",\n \"tsx\": \"^4.7.3\",\n \"typedoc\": \"^0.25.13\",\n \"typedoc-plugin-extras\": \"^3.0.0\",\n \"typedoc-plugin-rename-defaults\": \"^0.7.0\",\n \"typedoc-plugin-script-inject\": \"^2.0.0\",\n \"typescript\": \"^5.4.5\"\n },\n \"overrides\": {\n \"vm2\": \"npm:vm2-fixed@0.0.1\"\n }\n}\n"], + "sourcesContent": ["/**\n * @packageDocumentation\n **/\n\n// Copyright 2017-2022 the Short Unique ID authors. All rights reserved. Apache 2.0 license.\n\n// @ts-ignore\nimport {version} from '../package.json';\n\nexport interface ShortUniqueIdRanges {\n [k: string]: [number, number];\n};\n\nexport interface ShortUniqueIdRangesMap {\n [k: string]: ShortUniqueIdRanges;\n};\n\nexport type ShortUniqueIdDefaultDictionaries = 'number' | 'alpha' | 'alpha_lower' | 'alpha_upper' | 'alphanum' | 'alphanum_lower' | 'alphanum_upper' | 'hex';\n\n/**\n * ```js\n * {\n * dictionary: ['z', 'a', 'p', 'h', 'o', 'd', ...],\n * shuffle: false,\n * debug: false,\n * length: 6,\n * }\n * ```\n *
\n * @see {@link DEFAULT_OPTIONS}\n */\nexport interface ShortUniqueIdOptions {\n /** User-defined character dictionary */\n dictionary: string[] | ShortUniqueIdDefaultDictionaries;\n\n /** If true, sequentialUUID use the dictionary in the given order */\n shuffle: boolean;\n\n /** If true the instance will console.log useful info */\n debug: boolean;\n\n /** From 1 to infinity, the length you wish your UUID to be */\n length: number;\n\n /** From 0 to infinity, the current value for the sequential UUID counter */\n counter: number;\n};\n\n/**\n * 6 was chosen as the default UUID length since for most cases\n * it will be more than aptly suitable to provide millions of UUIDs\n * with a very low probability of producing a duplicate UUID.\n *\n * For example, with a dictionary including digits from 0 to 9,\n * as well as the alphabet from a to z both in UPPER and lower case,\n * the probability of generating a duplicate in 1,000,000 rounds\n * is ~0.00000002, or about 1 in 50,000,000.\n */\nexport const DEFAULT_UUID_LENGTH: number = 6;\n\nexport const DEFAULT_OPTIONS: ShortUniqueIdOptions = {\n dictionary: 'alphanum',\n shuffle: true,\n debug: false,\n length: DEFAULT_UUID_LENGTH,\n counter: 0,\n};\n\n/**\n * Generate random or sequential UUID of any length.\n *\n * ### Use as module\n *\n * ```js\n * // Deno (web module) Import\n * import ShortUniqueId from 'https://cdn.jsdelivr.net/npm/short-unique-id@latest/src/index.ts';\n *\n * // ES6 / TypeScript Import\n * import ShortUniqueId from 'short-unique-id';\n *\n * // or Node.js require\n * const ShortUniqueId = require('short-unique-id');\n *\n * // Instantiate\n * const uid = new ShortUniqueId();\n *\n * // Random UUID\n * console.log(uid.rnd());\n *\n * // Sequential UUID\n * console.log(uid.seq());\n * ```\n *\n * ### Use in browser\n *\n * ```html\n * \n * \n *\n * \n * \n * ```\n *\n * ### Options\n *\n * Options can be passed when instantiating `uid`:\n *\n * ```js\n * const options = { ... };\n *\n * const uid = new ShortUniqueId(options);\n * ```\n *\n * For more information take a look at the [ShortUniqueIdOptions type definition](/interfaces/shortuniqueidoptions.html).\n */\nexport default class ShortUniqueId {\n /** @hidden */\n static default: typeof ShortUniqueId = ShortUniqueId;\n\n public counter: number;\n public debug: boolean;\n public dict: string[];\n public version: string;\n public dictIndex: number = 0;\n public dictRange: number[] =[];\n public lowerBound: number = 0;\n public upperBound: number = 0;\n public dictLength: number = 0;\n public uuidLength: number;\n\n protected _digit_first_ascii: number = 48;\n protected _digit_last_ascii: number = 58;\n protected _alpha_lower_first_ascii: number = 97;\n protected _alpha_lower_last_ascii: number = 123;\n protected _hex_last_ascii: number = 103;\n protected _alpha_upper_first_ascii: number = 65;\n protected _alpha_upper_last_ascii: number = 91;\n\n protected _number_dict_ranges: ShortUniqueIdRanges = {\n digits: [this._digit_first_ascii, this._digit_last_ascii],\n };\n\n protected _alpha_dict_ranges: ShortUniqueIdRanges = {\n lowerCase: [this._alpha_lower_first_ascii, this._alpha_lower_last_ascii],\n upperCase: [this._alpha_upper_first_ascii, this._alpha_upper_last_ascii],\n };\n\n protected _alpha_lower_dict_ranges: ShortUniqueIdRanges = {\n lowerCase: [this._alpha_lower_first_ascii, this._alpha_lower_last_ascii],\n };\n\n protected _alpha_upper_dict_ranges: ShortUniqueIdRanges = {\n upperCase: [this._alpha_upper_first_ascii, this._alpha_upper_last_ascii],\n };\n\n protected _alphanum_dict_ranges: ShortUniqueIdRanges = {\n digits: [this._digit_first_ascii, this._digit_last_ascii],\n lowerCase: [this._alpha_lower_first_ascii, this._alpha_lower_last_ascii],\n upperCase: [this._alpha_upper_first_ascii, this._alpha_upper_last_ascii],\n };\n\n protected _alphanum_lower_dict_ranges: ShortUniqueIdRanges = {\n digits: [this._digit_first_ascii, this._digit_last_ascii],\n lowerCase: [this._alpha_lower_first_ascii, this._alpha_lower_last_ascii],\n };\n\n protected _alphanum_upper_dict_ranges: ShortUniqueIdRanges = {\n digits: [this._digit_first_ascii, this._digit_last_ascii],\n upperCase: [this._alpha_upper_first_ascii, this._alpha_upper_last_ascii],\n };\n\n protected _hex_dict_ranges: ShortUniqueIdRanges = {\n decDigits: [this._digit_first_ascii, this._digit_last_ascii],\n alphaDigits: [this._alpha_lower_first_ascii, this._hex_last_ascii],\n };\n\n protected _dict_ranges: ShortUniqueIdRangesMap = {\n _number_dict_ranges: this._number_dict_ranges,\n _alpha_dict_ranges: this._alpha_dict_ranges,\n _alpha_lower_dict_ranges: this._alpha_lower_dict_ranges,\n _alpha_upper_dict_ranges: this._alpha_upper_dict_ranges,\n _alphanum_dict_ranges: this._alphanum_dict_ranges,\n _alphanum_lower_dict_ranges: this._alphanum_lower_dict_ranges,\n _alphanum_upper_dict_ranges: this._alphanum_upper_dict_ranges,\n _hex_dict_ranges: this._hex_dict_ranges,\n };\n\n /* tslint:disable consistent-return */\n protected log = (...args: any[]): void => {\n const finalArgs = [...args];\n finalArgs[0] = `[short-unique-id] ${args[0]}`;\n /* tslint:disable no-console */\n if (this.debug === true) {\n if (typeof console !== 'undefined' && console !== null) {\n return console.log(...finalArgs);\n }\n }\n /* tslint:enable no-console */\n };\n /* tslint:enable consistent-return */\n\n protected _normalizeDictionary = (dictionary: string[] | ShortUniqueIdDefaultDictionaries, shuffle?: boolean): string[] => {\n let finalDict: string[];\n\n if (dictionary && Array.isArray(dictionary) && dictionary.length > 1) {\n finalDict = dictionary as string[];\n } else {\n finalDict = [];\n\n let i;\n\n this.dictIndex = i = 0;\n\n const rangesName = `_${dictionary as ShortUniqueIdDefaultDictionaries}_dict_ranges`;\n const ranges = this._dict_ranges[rangesName];\n\n Object.keys(ranges).forEach((rangeType) => {\n const rangeTypeKey = rangeType;\n\n this.dictRange = ranges[rangeTypeKey];\n\n this.lowerBound = this.dictRange[0];\n this.upperBound = this.dictRange[1];\n\n for (\n this.dictIndex = i = this.lowerBound;\n this.lowerBound <= this.upperBound ? i < this.upperBound : i > this.upperBound;\n this.dictIndex = this.lowerBound <= this.upperBound ? i += 1 : i -= 1\n ) {\n finalDict.push(String.fromCharCode(this.dictIndex));\n }\n });\n }\n\n if (shuffle) {\n // Shuffle Dictionary to remove selection bias.\n const PROBABILITY = 0.5;\n finalDict = finalDict.sort(() => Math.random() - PROBABILITY);\n }\n\n return finalDict;\n }\n\n /** Change the dictionary after initialization. */\n setDictionary = (dictionary: string[] | ShortUniqueIdDefaultDictionaries, shuffle?: boolean): void => {\n this.dict = this._normalizeDictionary(dictionary, shuffle);\n\n // Cache Dictionary Length for future usage.\n this.dictLength = this.dict.length;\n\n // Reset internal counter.\n this.setCounter(0);\n };\n\n seq = (): string => {\n return this.sequentialUUID();\n };\n\n /**\n * Generates UUID based on internal counter that's incremented after each ID generation.\n * @alias `const uid = new ShortUniqueId(); uid.seq();`\n */\n sequentialUUID = (): string => {\n let counterDiv: number;\n let counterRem: number;\n let id: string = '';\n\n counterDiv = this.counter;\n\n do {\n counterRem = counterDiv % this.dictLength;\n counterDiv = Math.trunc(counterDiv / this.dictLength);\n id += this.dict[counterRem];\n } while (counterDiv !== 0);\n\n this.counter += 1;\n\n return id;\n };\n\n rnd = (uuidLength: number = this.uuidLength || DEFAULT_UUID_LENGTH): string => {\n return this.randomUUID(uuidLength);\n };\n\n /**\n * Generates UUID by creating each part randomly.\n * @alias `const uid = new ShortUniqueId(); uid.rnd(uuidLength: number);`\n */\n randomUUID = (uuidLength: number = this.uuidLength || DEFAULT_UUID_LENGTH): string => {\n let id: string;\n let randomPartIdx: number;\n let j: number;\n\n if ((uuidLength === null || typeof uuidLength === 'undefined') || uuidLength < 1) {\n throw new Error('Invalid UUID Length Provided');\n }\n\n const isPositive = uuidLength >= 0;\n\n // Generate random ID parts from Dictionary.\n id = '';\n for (\n j = 0;\n j < uuidLength;\n j += 1\n ) {\n randomPartIdx = parseInt(\n (Math.random() * this.dictLength).toFixed(0),\n 10,\n ) % this.dictLength;\n id += this.dict[randomPartIdx];\n }\n\n // Return random generated ID.\n return id;\n };\n\n fmt = (format: string, date?: Date): string => {\n return this.formattedUUID(format, date);\n };\n\n /**\n * Generates custom UUID with the provided format string.\n * @alias `const uid = new ShortUniqueId(); uid.fmt(format: string);`\n */\n formattedUUID = (format: string, date?: Date): string => {\n const fnMap = {\n '$r': this.randomUUID,\n '$s': this.sequentialUUID,\n '$t': this.stamp,\n };\n\n const result = format.replace(\n /\\$[rs]\\d{0,}|\\$t0|\\$t[1-9]\\d{1,}/g,\n (m) => {\n const fn = m.slice(0, 2);\n const len = parseInt(m.slice(2), 10);\n\n if (fn === '$s') {\n return fnMap[fn]().padStart(len, '0');\n }\n\n if (fn === '$t' && date) {\n return fnMap[fn](len, date);\n }\n\n return fnMap[fn as keyof typeof fnMap](len);\n },\n );\n\n return result;\n };\n\n /**\n * Calculates total number of possible UUIDs.\n *\n * Given that:\n *\n * - `H` is the total number of possible UUIDs\n * - `n` is the number of unique characters in the dictionary\n * - `l` is the UUID length\n *\n * Then `H` is defined as `n` to the power of `l`:\n *\n *
\n * \n *
\n *\n * This function returns `H`.\n */\n availableUUIDs = (uuidLength: number = this.uuidLength): number => {\n return parseFloat(\n Math.pow([...new Set(this.dict)].length, uuidLength).toFixed(0),\n );\n };\n\n /**\n * Calculates approximate number of hashes before first collision.\n *\n * Given that:\n *\n * - `H` is the total number of possible UUIDs, or in terms of this library,\n * the result of running `availableUUIDs()`\n * - the expected number of values we have to choose before finding the\n * first collision can be expressed as the quantity `Q(H)`\n *\n * Then `Q(H)` can be approximated as the square root of the product of half\n * of pi times `H`:\n *\n *
\n * \n *
\n *\n * This function returns `Q(H)`.\n * \n * (see [Poisson distribution](https://en.wikipedia.org/wiki/Poisson_distribution))\n */\n approxMaxBeforeCollision = (rounds: number = this.availableUUIDs(this.uuidLength)): number => {\n return parseFloat(\n Math.sqrt((Math.PI / 2) * rounds).toFixed(20),\n );\n };\n\n /**\n * Calculates probability of generating duplicate UUIDs (a collision) in a\n * given number of UUID generation rounds.\n *\n * Given that:\n *\n * - `r` is the maximum number of times that `randomUUID()` will be called,\n * or better said the number of _rounds_\n * - `H` is the total number of possible UUIDs, or in terms of this library,\n * the result of running `availableUUIDs()`\n *\n * Then the probability of collision `p(r; H)` can be approximated as the result\n * of dividing the square root of the product of half of pi times `r` by `H`:\n *\n *
\n * \n *
\n *\n * This function returns `p(r; H)`.\n * \n * (see [Poisson distribution](https://en.wikipedia.org/wiki/Poisson_distribution))\n *\n * (Useful if you are wondering _\"If I use this lib and expect to perform at most\n * `r` rounds of UUID generations, what is the probability that I will hit a duplicate UUID?\"_.)\n */\n collisionProbability = (\n rounds: number = this.availableUUIDs(this.uuidLength),\n uuidLength: number = this.uuidLength,\n ): number => {\n return parseFloat(\n (\n this.approxMaxBeforeCollision(rounds) / this.availableUUIDs(uuidLength)\n ).toFixed(20),\n );\n };\n\n /**\n * Calculate a \"uniqueness\" score (from 0 to 1) of UUIDs based on size of\n * dictionary and chosen UUID length.\n *\n * Given that:\n *\n * - `H` is the total number of possible UUIDs, or in terms of this library,\n * the result of running `availableUUIDs()`\n * - `Q(H)` is the approximate number of hashes before first collision,\n * or in terms of this library, the result of running `approxMaxBeforeCollision()`\n *\n * Then `uniqueness` can be expressed as the additive inverse of the probability of\n * generating a \"word\" I had previously generated (a duplicate) at any given iteration\n * up to the the total number of possible UUIDs expressed as the quotiend of `Q(H)` and `H`:\n *\n *
\n * \n *
\n *\n * (Useful if you need a value to rate the \"quality\" of the combination of given dictionary\n * and UUID length. The closer to 1, higher the uniqueness and thus better the quality.)\n */\n uniqueness = (rounds: number = this.availableUUIDs(this.uuidLength)): number => {\n const score = parseFloat(\n (1 - (\n this.approxMaxBeforeCollision(rounds) / rounds\n )).toFixed(20),\n );\n return (\n score > 1\n ) ? (\n 1\n ) : (\n (score < 0) ? 0 : score\n );\n };\n\n /**\n * Return the version of this module.\n */\n getVersion = (): string => {\n return this.version;\n };\n\n /**\n * Generates a UUID with a timestamp that can be extracted using `uid.parseStamp(stampString);`.\n * \n * ```js\n * const uidWithTimestamp = uid.stamp(32);\n * console.log(uidWithTimestamp);\n * // GDa608f973aRCHLXQYPTbKDbjDeVsSb3\n * \n * console.log(uid.parseStamp(uidWithTimestamp));\n * // 2021-05-03T06:24:58.000Z\n * ```\n */\n stamp = (finalLength: number, date?: Date): string => {\n const hexStamp = Math.floor(+(date || new Date()) / 1000).toString(16);\n\n if (typeof finalLength === 'number' && finalLength === 0) {\n return hexStamp;\n }\n\n if (typeof finalLength !== 'number' || finalLength < 10) {\n throw new Error(\n [\n 'Param finalLength must be a number greater than or equal to 10,',\n 'or 0 if you want the raw hexadecimal timestamp',\n ].join('\\n')\n );\n }\n\n const idLength = finalLength - 9;\n\n const rndIdx = Math.round(Math.random() * ((idLength > 15) ? 15 : idLength));\n\n const id = this.randomUUID(idLength);\n\n return `${id.substring(0, rndIdx)}${hexStamp}${id.substring(rndIdx)}${rndIdx.toString(16)}`;\n };\n\n /**\n * Extracts the date embeded in a UUID generated using the `uid.stamp(finalLength);` method.\n * \n * ```js\n * const uidWithTimestamp = uid.stamp(32);\n * console.log(uidWithTimestamp);\n * // GDa608f973aRCHLXQYPTbKDbjDeVsSb3\n * \n * console.log(uid.parseStamp(uidWithTimestamp));\n * // 2021-05-03T06:24:58.000Z\n * ```\n */\n parseStamp = (suid: string, format?: string): Date => {\n if (format && !(/t0|t[1-9]\\d{1,}/).test(format)) {\n throw new Error('Cannot extract date from a formated UUID with no timestamp in the format');\n }\n\n const stamp = (\n format\n ) ? (\n format.replace(\n /\\$[rs]\\d{0,}|\\$t0|\\$t[1-9]\\d{1,}/g,\n (m) => {\n const fnMap = {\n '$r': (len: number) => [...Array(len)].map(() => 'r').join(''),\n '$s': (len: number) => [...Array(len)].map(() => 's').join(''),\n '$t': (len: number) => [...Array(len)].map(() => 't').join(''),\n };\n\n const fn = m.slice(0, 2);\n const len = parseInt(m.slice(2), 10);\n\n return fnMap[fn as keyof typeof fnMap](len);\n },\n ).replace(\n /^(.*?)(t{8,})(.*)$/g,\n (_m, p1, p2) => {\n return suid.substring(p1.length, p1.length + p2.length);\n },\n )\n ) : (\n suid\n );\n\n if (stamp.length === 8) {\n return new Date(parseInt(stamp, 16) * 1000);\n }\n\n if (stamp.length < 10) {\n throw new Error('Stamp length invalid');\n }\n\n const rndIdx = parseInt(stamp.substring(stamp.length - 1), 16);\n\n return new Date(parseInt(stamp.substring(rndIdx, rndIdx + 8), 16) * 1000);\n };\n\n /**\n * Set the counter to a specific value.\n */\n setCounter = (counter: number): void => {\n this.counter = counter;\n };\n\n /**\n * Validate given UID contains only characters from the instanced dictionary or optionally provided dictionary.\n */\n validate = (uid: string, dictionary?: string[] | ShortUniqueIdDefaultDictionaries): boolean => {\n const finalDictionary = dictionary ? this._normalizeDictionary(dictionary) : this.dict;\n\n return uid.split('').every((c) => finalDictionary.includes(c));\n };\n\n constructor(argOptions: Partial = {}) {\n const options: ShortUniqueIdOptions = {\n ...DEFAULT_OPTIONS,\n ...argOptions as Partial,\n };\n\n this.counter = 0;\n this.debug = false;\n this.dict = [];\n this.version = version;\n\n const {\n dictionary,\n shuffle,\n length,\n counter,\n } = options;\n\n this.uuidLength = length;\n\n this.setDictionary(dictionary, shuffle);\n this.setCounter(counter);\n\n this.debug = options.debug;\n this.log(this.dict);\n this.log(\n `Generator instantiated with Dictionary Size ${this.dictLength} and counter set to ${this.counter}`\n );\n\n this.log = this.log.bind(this);\n this.setDictionary = this.setDictionary.bind(this);\n this.setCounter = this.setCounter.bind(this);\n this.seq = this.seq.bind(this);\n this.sequentialUUID = this.sequentialUUID.bind(this);\n this.rnd = this.rnd.bind(this);\n this.randomUUID = this.randomUUID.bind(this);\n this.fmt = this.fmt.bind(this);\n this.formattedUUID = this.formattedUUID.bind(this);\n this.availableUUIDs = this.availableUUIDs.bind(this);\n this.approxMaxBeforeCollision = this.approxMaxBeforeCollision.bind(this);\n this.collisionProbability = this.collisionProbability.bind(this);\n this.uniqueness = this.uniqueness.bind(this);\n this.getVersion = this.getVersion.bind(this);\n this.stamp = this.stamp.bind(this);\n this.parseStamp = this.parseStamp.bind(this);\n\n return this;\n }\n}\n", "{\n \"name\": \"short-unique-id\",\n \"version\": \"5.2.0\",\n \"description\": \"Generate random or sequential UUID of any length\",\n \"keywords\": [\n \"short\",\n \"random\",\n \"uid\",\n \"uuid\",\n \"guid\",\n \"node\",\n \"unique id\",\n \"generator\",\n \"tiny\"\n ],\n \"bin\": {\n \"short-unique-id\": \"bin/short-unique-id\",\n \"suid\": \"bin/short-unique-id\"\n },\n \"main\": \"dist/short-unique-id.js\",\n \"types\": \"dist/short-unique-id.d.ts\",\n \"homepage\": \"https://shortunique.id\",\n \"repository\": {\n \"type\": \"git\",\n \"url\": \"https://github.com/jeanlescure/short-unique-id\"\n },\n \"license\": \"Apache-2.0\",\n \"runkitExampleFilename\": \"./runkit.js\",\n \"scripts\": {\n \"test\": \"tsx ./src/test.ts\",\n \"test:local\": \"tsx ./src/test.ts && tsx --tsconfig ./specs/esm/tsconfig.json ./specs/esm/import.spec.ts && ./scripts/cjs-test\",\n \"build\": \"./scripts/build\",\n \"docs\": \"./scripts/docs\",\n \"release\": \"release-it\"\n },\n \"release-it\": {\n \"git\": {\n \"changelog\": \"auto-changelog --stdout -l false -u -t ./assets/changelog-compact.hbs\"\n },\n \"hooks\": {\n \"after:bump\": \"./scripts/release\"\n },\n \"npm\": {\n \"publish\": false\n }\n },\n \"files\": [\n \"bin\",\n \"dist\",\n \"runkit.js\",\n \"package.json\"\n ],\n \"devDependencies\": {\n \"@types/node\": \"^20.12.7\",\n \"auto-changelog\": \"^2.4.0\",\n \"esbuild\": \"^0.18.10\",\n \"refup\": \"^1.1.0\",\n \"release-it\": \"^15.11.0\",\n \"tslib\": \"^2.6.2\",\n \"tsx\": \"^4.7.3\",\n \"typedoc\": \"^0.25.13\",\n \"typedoc-plugin-extras\": \"^3.0.0\",\n \"typedoc-plugin-rename-defaults\": \"^0.7.0\",\n \"typedoc-plugin-script-inject\": \"^2.0.0\",\n \"typescript\": \"^5.4.5\"\n },\n \"overrides\": {\n \"vm2\": \"npm:vm2-fixed@0.0.1\"\n }\n}\n"], "mappings": ";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACEE,gBAAW;;;ADwDN,MAAM,sBAA8B;AAEpC,MAAM,kBAAwC;AAAA,IACnD,YAAY;AAAA,IACZ,SAAS;AAAA,IACT,OAAO;AAAA,IACP,QAAQ;AAAA,IACR,SAAS;AAAA,EACX;AA0DA,M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,eAAe,KAAK,IAAI;AACnD,WAAK,MAAM,KAAK,IAAI,KAAK,IAAI;AAC7B,WAAK,aAAa,KAAK,WAAW,KAAK,IAAI;AAC3C,WAAK,MAAM,KAAK,IAAI,KAAK,IAAI;AAC7B,WAAK,gBAAgB,KAAK,cAAc,KAAK,IAAI;AACjD,WAAK,iBAAiB,KAAK,eAAe,KAAK,IAAI;AACnD,WAAK,2BAA2B,KAAK,yBAAyB,KAAK,IAAI;AACvE,WAAK,uBAAuB,KAAK,qBAAqB,KAAK,IAAI;AAC/D,WAAK,aAAa,KAAK,WAAW,KAAK,IAAI;AAC3C,WAAK,aAAa,KAAK,WAAW,KAAK,IAAI;AAC3C,WAAK,QAAQ,KAAK,MAAM,KAAK,IAAI;AACjC,WAAK,aAAa,KAAK,WAAW,KAAK,IAAI;AAE3C,aAAO;AAAA,IACT;AAAA,EACF;AA5gBE;AAAA,gBAFmB,gBAEZ,WAAgC;AAFzC,MAAqB,gBAArB;", "names": ["len"] } diff --git a/dist/short-unique-id.min.js b/dist/short-unique-id.min.js index 938cf76..82e4354 100644 --- a/dist/short-unique-id.min.js +++ b/dist/short-unique-id.min.js @@ -1,3 +1,3 @@ -"use strict";var ShortUniqueId=(()=>{var l=Object.defineProperty;var D=Object.getOwnPropertyDescriptor;var w=Object.getOwnPropertyNames,b=Object.getOwnPropertySymbols;var f=Object.prototype.hasOwnProperty,q=Object.prototype.propertyIsEnumerable;var g=(a,t,i)=>t in a?l(a,t,{enumerable:!0,configurable:!0,writable:!0,value:i}):a[t]=i,m=(a,t)=>{for(var i in t||(t={}))f.call(t,i)&&g(a,i,t[i]);if(b)for(var i of b(t))q.call(t,i)&&g(a,i,t[i]);return a};var x=(a,t)=>{for(var i in t)l(a,i,{get:t[i],enumerable:!0})},y=(a,t,i,s)=>{if(t&&typeof t=="object"||typeof t=="function")for(let r of w(t))!f.call(a,r)&&r!==i&&l(a,r,{get:()=>t[r],enumerable:!(s=D(t,r))||s.enumerable});return a};var S=a=>y(l({},"__esModule",{value:!0}),a);var e=(a,t,i)=>(g(a,typeof t!="symbol"?t+"":t,i),i);var $={};x($,{DEFAULT_OPTIONS:()=>I,DEFAULT_UUID_LENGTH:()=>d,default:()=>p});var U="5.1.1";var d=6,I={dictionary:"alphanum",shuffle:!0,debug:!1,length:d,counter:0},c=class c{constructor(t={}){e(this,"counter");e(this,"debug");e(this,"dict");e(this,"version");e(this,"dictIndex",0);e(this,"dictRange",[]);e(this,"lowerBound",0);e(this,"upperBound",0);e(this,"dictLength",0);e(this,"uuidLength");e(this,"_digit_first_ascii",48);e(this,"_digit_last_ascii",58);e(this,"_alpha_lower_first_ascii",97);e(this,"_alpha_lower_last_ascii",123);e(this,"_hex_last_ascii",103);e(this,"_alpha_upper_first_ascii",65);e(this,"_alpha_upper_last_ascii",91);e(this,"_number_dict_ranges",{digits:[this._digit_first_ascii,this._digit_last_ascii]});e(this,"_alpha_dict_ranges",{lowerCase:[this._alpha_lower_first_ascii,this._alpha_lower_last_ascii],upperCase:[this._alpha_upper_first_ascii,this._alpha_upper_last_ascii]});e(this,"_alpha_lower_dict_ranges",{lowerCase:[this._alpha_lower_first_ascii,this._alpha_lower_last_ascii]});e(this,"_alpha_upper_dict_ranges",{upperCase:[this._alpha_upper_first_ascii,this._alpha_upper_last_ascii]});e(this,"_alphanum_dict_ranges",{digits:[this._digit_first_ascii,this._digit_last_ascii],lowerCase:[this._alpha_lower_first_ascii,this._alpha_lower_last_ascii],upperCase:[this._alpha_upper_first_ascii,this._alpha_upper_last_ascii]});e(this,"_alphanum_lower_dict_ranges",{digits:[this._digit_first_ascii,this._digit_last_ascii],lowerCase:[this._alpha_lower_first_ascii,this._alpha_lower_last_ascii]});e(this,"_alphanum_upper_dict_ranges",{digits:[this._digit_first_ascii,this._digit_last_ascii],upperCase:[this._alpha_upper_first_ascii,this._alpha_upper_last_ascii]});e(this,"_hex_dict_ranges",{decDigits:[this._digit_first_ascii,this._digit_last_ascii],alphaDigits:[this._alpha_lower_first_ascii,this._hex_last_ascii]});e(this,"_dict_ranges",{_number_dict_ranges:this._number_dict_ranges,_alpha_dict_ranges:this._alpha_dict_ranges,_alpha_lower_dict_ranges:this._alpha_lower_dict_ranges,_alpha_upper_dict_ranges:this._alpha_upper_dict_ranges,_alphanum_dict_ranges:this._alphanum_dict_ranges,_alphanum_lower_dict_ranges:this._alphanum_lower_dict_ranges,_alphanum_upper_dict_ranges:this._alphanum_upper_dict_ranges,_hex_dict_ranges:this._hex_dict_ranges});e(this,"log",(...t)=>{let i=[...t];if(i[0]=`[short-unique-id] ${t[0]}`,this.debug===!0&&typeof console<"u"&&console!==null)return console.log(...i)});e(this,"_normalizeDictionary",(t,i)=>{let s;if(t&&Array.isArray(t)&&t.length>1)s=t;else{s=[];let r;this.dictIndex=r=0;let o=`_${t}_dict_ranges`,n=this._dict_ranges[o];Object.keys(n).forEach(h=>{let _=h;for(this.dictRange=n[_],this.lowerBound=this.dictRange[0],this.upperBound=this.dictRange[1],this.dictIndex=r=this.lowerBound;this.lowerBound<=this.upperBound?rthis.upperBound;this.dictIndex=this.lowerBound<=this.upperBound?r+=1:r-=1)s.push(String.fromCharCode(this.dictIndex))})}return i&&(s=s.sort(()=>Math.random()-.5)),s});e(this,"setDictionary",(t,i)=>{this.dict=this._normalizeDictionary(t,i),this.dictLength=this.dict.length,this.setCounter(0)});e(this,"seq",()=>this.sequentialUUID());e(this,"sequentialUUID",()=>{let t,i,s="";t=this.counter;do i=t%this.dictLength,t=Math.trunc(t/this.dictLength),s+=this.dict[i];while(t!==0);return this.counter+=1,s});e(this,"rnd",(t=this.uuidLength||d)=>this.randomUUID(t));e(this,"randomUUID",(t=this.uuidLength||d)=>{let i,s,r;if(t===null||typeof t>"u"||t<1)throw new Error("Invalid UUID Length Provided");let o=t>=0;for(i="",r=0;rthis.formattedUUID(t,i));e(this,"formattedUUID",(t,i)=>{let s={$r:this.randomUUID,$s:this.sequentialUUID,$t:this.stamp};return t.replace(/\$[rs]\d{0,}|\$t0|\$t[1-9]\d{1,}/g,o=>{let n=o.slice(0,2),h=parseInt(o.slice(2),10);return n==="$s"?s[n]().padStart(h,"0"):n==="$t"&&i?s[n](h,i):s[n](h)})});e(this,"availableUUIDs",(t=this.uuidLength)=>parseFloat(Math.pow([...new Set(this.dict)].length,t).toFixed(0)));e(this,"approxMaxBeforeCollision",(t=this.availableUUIDs(this.uuidLength))=>parseFloat(Math.sqrt(Math.PI/2*t).toFixed(20)));e(this,"collisionProbability",(t=this.availableUUIDs(this.uuidLength),i=this.uuidLength)=>parseFloat((this.approxMaxBeforeCollision(t)/this.availableUUIDs(i)).toFixed(20)));e(this,"uniqueness",(t=this.availableUUIDs(this.uuidLength))=>{let i=parseFloat((1-this.approxMaxBeforeCollision(t)/t).toFixed(20));return i>1?1:i<0?0:i});e(this,"getVersion",()=>this.version);e(this,"stamp",(t,i)=>{let s=Math.floor(+(i||new Date)/1e3).toString(16);if(typeof t=="number"&&t===0)return s;if(typeof t!="number"||t<10)throw new Error(["Param finalLength must be a number greater than or equal to 10,","or 0 if you want the raw hexadecimal timestamp"].join(` +"use strict";var ShortUniqueId=(()=>{var l=Object.defineProperty;var D=Object.getOwnPropertyDescriptor;var w=Object.getOwnPropertyNames,b=Object.getOwnPropertySymbols;var f=Object.prototype.hasOwnProperty,q=Object.prototype.propertyIsEnumerable;var g=(a,t,i)=>t in a?l(a,t,{enumerable:!0,configurable:!0,writable:!0,value:i}):a[t]=i,m=(a,t)=>{for(var i in t||(t={}))f.call(t,i)&&g(a,i,t[i]);if(b)for(var i of b(t))q.call(t,i)&&g(a,i,t[i]);return a};var x=(a,t)=>{for(var i in t)l(a,i,{get:t[i],enumerable:!0})},y=(a,t,i,s)=>{if(t&&typeof t=="object"||typeof t=="function")for(let r of w(t))!f.call(a,r)&&r!==i&&l(a,r,{get:()=>t[r],enumerable:!(s=D(t,r))||s.enumerable});return a};var S=a=>y(l({},"__esModule",{value:!0}),a);var e=(a,t,i)=>(g(a,typeof t!="symbol"?t+"":t,i),i);var $={};x($,{DEFAULT_OPTIONS:()=>I,DEFAULT_UUID_LENGTH:()=>d,default:()=>p});var U="5.2.0";var d=6,I={dictionary:"alphanum",shuffle:!0,debug:!1,length:d,counter:0},c=class c{constructor(t={}){e(this,"counter");e(this,"debug");e(this,"dict");e(this,"version");e(this,"dictIndex",0);e(this,"dictRange",[]);e(this,"lowerBound",0);e(this,"upperBound",0);e(this,"dictLength",0);e(this,"uuidLength");e(this,"_digit_first_ascii",48);e(this,"_digit_last_ascii",58);e(this,"_alpha_lower_first_ascii",97);e(this,"_alpha_lower_last_ascii",123);e(this,"_hex_last_ascii",103);e(this,"_alpha_upper_first_ascii",65);e(this,"_alpha_upper_last_ascii",91);e(this,"_number_dict_ranges",{digits:[this._digit_first_ascii,this._digit_last_ascii]});e(this,"_alpha_dict_ranges",{lowerCase:[this._alpha_lower_first_ascii,this._alpha_lower_last_ascii],upperCase:[this._alpha_upper_first_ascii,this._alpha_upper_last_ascii]});e(this,"_alpha_lower_dict_ranges",{lowerCase:[this._alpha_lower_first_ascii,this._alpha_lower_last_ascii]});e(this,"_alpha_upper_dict_ranges",{upperCase:[this._alpha_upper_first_ascii,this._alpha_upper_last_ascii]});e(this,"_alphanum_dict_ranges",{digits:[this._digit_first_ascii,this._digit_last_ascii],lowerCase:[this._alpha_lower_first_ascii,this._alpha_lower_last_ascii],upperCase:[this._alpha_upper_first_ascii,this._alpha_upper_last_ascii]});e(this,"_alphanum_lower_dict_ranges",{digits:[this._digit_first_ascii,this._digit_last_ascii],lowerCase:[this._alpha_lower_first_ascii,this._alpha_lower_last_ascii]});e(this,"_alphanum_upper_dict_ranges",{digits:[this._digit_first_ascii,this._digit_last_ascii],upperCase:[this._alpha_upper_first_ascii,this._alpha_upper_last_ascii]});e(this,"_hex_dict_ranges",{decDigits:[this._digit_first_ascii,this._digit_last_ascii],alphaDigits:[this._alpha_lower_first_ascii,this._hex_last_ascii]});e(this,"_dict_ranges",{_number_dict_ranges:this._number_dict_ranges,_alpha_dict_ranges:this._alpha_dict_ranges,_alpha_lower_dict_ranges:this._alpha_lower_dict_ranges,_alpha_upper_dict_ranges:this._alpha_upper_dict_ranges,_alphanum_dict_ranges:this._alphanum_dict_ranges,_alphanum_lower_dict_ranges:this._alphanum_lower_dict_ranges,_alphanum_upper_dict_ranges:this._alphanum_upper_dict_ranges,_hex_dict_ranges:this._hex_dict_ranges});e(this,"log",(...t)=>{let i=[...t];if(i[0]=`[short-unique-id] ${t[0]}`,this.debug===!0&&typeof console<"u"&&console!==null)return console.log(...i)});e(this,"_normalizeDictionary",(t,i)=>{let s;if(t&&Array.isArray(t)&&t.length>1)s=t;else{s=[];let r;this.dictIndex=r=0;let o=`_${t}_dict_ranges`,n=this._dict_ranges[o];Object.keys(n).forEach(h=>{let _=h;for(this.dictRange=n[_],this.lowerBound=this.dictRange[0],this.upperBound=this.dictRange[1],this.dictIndex=r=this.lowerBound;this.lowerBound<=this.upperBound?rthis.upperBound;this.dictIndex=this.lowerBound<=this.upperBound?r+=1:r-=1)s.push(String.fromCharCode(this.dictIndex))})}return i&&(s=s.sort(()=>Math.random()-.5)),s});e(this,"setDictionary",(t,i)=>{this.dict=this._normalizeDictionary(t,i),this.dictLength=this.dict.length,this.setCounter(0)});e(this,"seq",()=>this.sequentialUUID());e(this,"sequentialUUID",()=>{let t,i,s="";t=this.counter;do i=t%this.dictLength,t=Math.trunc(t/this.dictLength),s+=this.dict[i];while(t!==0);return this.counter+=1,s});e(this,"rnd",(t=this.uuidLength||d)=>this.randomUUID(t));e(this,"randomUUID",(t=this.uuidLength||d)=>{let i,s,r;if(t===null||typeof t>"u"||t<1)throw new Error("Invalid UUID Length Provided");let o=t>=0;for(i="",r=0;rthis.formattedUUID(t,i));e(this,"formattedUUID",(t,i)=>{let s={$r:this.randomUUID,$s:this.sequentialUUID,$t:this.stamp};return t.replace(/\$[rs]\d{0,}|\$t0|\$t[1-9]\d{1,}/g,o=>{let n=o.slice(0,2),h=parseInt(o.slice(2),10);return n==="$s"?s[n]().padStart(h,"0"):n==="$t"&&i?s[n](h,i):s[n](h)})});e(this,"availableUUIDs",(t=this.uuidLength)=>parseFloat(Math.pow([...new Set(this.dict)].length,t).toFixed(0)));e(this,"approxMaxBeforeCollision",(t=this.availableUUIDs(this.uuidLength))=>parseFloat(Math.sqrt(Math.PI/2*t).toFixed(20)));e(this,"collisionProbability",(t=this.availableUUIDs(this.uuidLength),i=this.uuidLength)=>parseFloat((this.approxMaxBeforeCollision(t)/this.availableUUIDs(i)).toFixed(20)));e(this,"uniqueness",(t=this.availableUUIDs(this.uuidLength))=>{let i=parseFloat((1-this.approxMaxBeforeCollision(t)/t).toFixed(20));return i>1?1:i<0?0:i});e(this,"getVersion",()=>this.version);e(this,"stamp",(t,i)=>{let s=Math.floor(+(i||new Date)/1e3).toString(16);if(typeof t=="number"&&t===0)return s;if(typeof t!="number"||t<10)throw new Error(["Param finalLength must be a number greater than or equal to 10,","or 0 if you want the raw hexadecimal timestamp"].join(` `));let r=t-9,o=Math.round(Math.random()*(r>15?15:r)),n=this.randomUUID(r);return`${n.substring(0,o)}${s}${n.substring(o)}${o.toString(16)}`});e(this,"parseStamp",(t,i)=>{if(i&&!/t0|t[1-9]\d{1,}/.test(i))throw new Error("Cannot extract date from a formated UUID with no timestamp in the format");let s=i?i.replace(/\$[rs]\d{0,}|\$t0|\$t[1-9]\d{1,}/g,o=>{let n={$r:u=>[...Array(u)].map(()=>"r").join(""),$s:u=>[...Array(u)].map(()=>"s").join(""),$t:u=>[...Array(u)].map(()=>"t").join("")},h=o.slice(0,2),_=parseInt(o.slice(2),10);return n[h](_)}).replace(/^(.*?)(t{8,})(.*)$/g,(o,n,h)=>t.substring(n.length,n.length+h.length)):t;if(s.length===8)return new Date(parseInt(s,16)*1e3);if(s.length<10)throw new Error("Stamp length invalid");let r=parseInt(s.substring(s.length-1),16);return new Date(parseInt(s.substring(r,r+8),16)*1e3)});e(this,"setCounter",t=>{this.counter=t});e(this,"validate",(t,i)=>{let s=i?this._normalizeDictionary(i):this.dict;return t.split("").every(r=>s.includes(r))});let i=m(m({},I),t);this.counter=0,this.debug=!1,this.dict=[],this.version=U;let{dictionary:s,shuffle:r,length:o,counter:n}=i;return this.uuidLength=o,this.setDictionary(s,r),this.setCounter(n),this.debug=i.debug,this.log(this.dict),this.log(`Generator instantiated with Dictionary Size ${this.dictLength} and counter set to ${this.counter}`),this.log=this.log.bind(this),this.setDictionary=this.setDictionary.bind(this),this.setCounter=this.setCounter.bind(this),this.seq=this.seq.bind(this),this.sequentialUUID=this.sequentialUUID.bind(this),this.rnd=this.rnd.bind(this),this.randomUUID=this.randomUUID.bind(this),this.fmt=this.fmt.bind(this),this.formattedUUID=this.formattedUUID.bind(this),this.availableUUIDs=this.availableUUIDs.bind(this),this.approxMaxBeforeCollision=this.approxMaxBeforeCollision.bind(this),this.collisionProbability=this.collisionProbability.bind(this),this.uniqueness=this.uniqueness.bind(this),this.getVersion=this.getVersion.bind(this),this.stamp=this.stamp.bind(this),this.parseStamp=this.parseStamp.bind(this),this}};e(c,"default",c);var p=c;return S($);})(); 'undefined'!=typeof module&&(module.exports=ShortUniqueId.default),'undefined'!=typeof window&&(ShortUniqueId=ShortUniqueId.default); \ No newline at end of file diff --git a/docs/classes/ShortUniqueId.html b/docs/classes/ShortUniqueId.html index a404a2a..7c5b051 100644 --- a/docs/classes/ShortUniqueId.html +++ b/docs/classes/ShortUniqueId.html @@ -1,4 +1,4 @@ -ShortUniqueId | short-unique-id - v5.1.1

Generate random or sequential UUID of any length.

+ShortUniqueId | short-unique-id - v5.2.0

Generate random or sequential UUID of any length.

Use as module

// Deno (web module) Import
import ShortUniqueId from 'https://cdn.jsdelivr.net/npm/short-unique-id@latest/src/index.ts';

// ES6 / TypeScript Import
import ShortUniqueId from 'short-unique-id';

// or Node.js require
const ShortUniqueId = require('short-unique-id');

// Instantiate
const uid = new ShortUniqueId();

// Random UUID
console.log(uid.rnd());

// Sequential UUID
console.log(uid.seq());

Use in browser

<!-- Import -->
<script src="https://cdn.jsdelivr.net/npm/short-unique-id@latest/dist/short-unique-id.min.js"></script>

<!-- Usage -->
<script>
// Instantiate
var uid = new ShortUniqueId();

// Random UUID
document.write(uid.rnd());

// Sequential UUID
document.write(uid.seq());
</script> @@ -7,7 +7,7 @@
const options = { ... };

const uid = new ShortUniqueId(options);

For more information take a look at the ShortUniqueIdOptions type definition.

-

Constructors

Constructors

Properties

Constructors

Properties

counter: number
debug: boolean
dict: string[]
dictIndex: number = 0
dictLength: number = 0
dictRange: number[] = []
lowerBound: number = 0
upperBound: number = 0
uuidLength: number
version: string

Methods

  • Calculates approximate number of hashes before first collision.

    +

Constructors

Properties

counter: number
debug: boolean
dict: string[]
dictIndex: number = 0
dictLength: number = 0
dictRange: number[] = []
lowerBound: number = 0
upperBound: number = 0
uuidLength: number
version: string

Methods

  • Calculates approximate number of hashes before first collision.

    Given that:

    • H is the total number of possible UUIDs, or in terms of this library, @@ -50,7 +50,7 @@

      This function returns Q(H).

      (see Poisson distribution)

      -

    Parameters

    • rounds: number = ...

    Returns number

  • Calculates total number of possible UUIDs.

    +

    Parameters

    • rounds: number = ...

    Returns number

  • Calculates total number of possible UUIDs.

    Given that:

    • H is the total number of possible UUIDs
    • @@ -63,7 +63,7 @@

    This function returns H.

    -

Parameters

  • uuidLength: number = ...

Returns number

  • Calculates probability of generating duplicate UUIDs (a collision) in a +

    Parameters

    • uuidLength: number = ...

    Returns number

  • Calculates probability of generating duplicate UUIDs (a collision) in a given number of UUID generation rounds.

    Given that:

      @@ -82,22 +82,22 @@

      (see Poisson distribution)

      (Useful if you are wondering "If I use this lib and expect to perform at most r rounds of UUID generations, what is the probability that I will hit a duplicate UUID?".)

      -

    Parameters

    • rounds: number = ...
    • uuidLength: number = ...

    Returns number

  • Parameters

    • format: string
    • Optional date: Date

    Returns string

  • Generates custom UUID with the provided format string.

    +

    Parameters

    • rounds: number = ...
    • uuidLength: number = ...

    Returns number

  • Parameters

    • format: string
    • Optional date: Date

    Returns string

  • Generates custom UUID with the provided format string.

    Parameters

    • format: string
    • Optional date: Date

    Returns string

    Alias

    const uid = new ShortUniqueId(); uid.fmt(format: string);

    -
  • Return the version of this module.

    -

    Returns string

  • Extracts the date embeded in a UUID generated using the uid.stamp(finalLength); method.

    +
  • Return the version of this module.

    +

    Returns string

  • Extracts the date embeded in a UUID generated using the uid.stamp(finalLength); method.

     const uidWithTimestamp = uid.stamp(32);
    console.log(uidWithTimestamp);
    // GDa608f973aRCHLXQYPTbKDbjDeVsSb3

    console.log(uid.parseStamp(uidWithTimestamp));
    // 2021-05-03T06:24:58.000Z
    -

    Parameters

    • suid: string
    • Optional format: string

    Returns Date

  • Generates UUID by creating each part randomly.

    +

    Parameters

    • suid: string
    • Optional format: string

    Returns Date

  • Generates UUID by creating each part randomly.

    Parameters

    • uuidLength: number = ...

    Returns string

    Alias

    const uid = new ShortUniqueId(); uid.rnd(uuidLength: number);

    -
  • Parameters

    • uuidLength: number = ...

    Returns string

  • Generates UUID based on internal counter that's incremented after each ID generation.

    +
  • Parameters

    • uuidLength: number = ...

    Returns string

  • Generates UUID based on internal counter that's incremented after each ID generation.

    Returns string

    Alias

    const uid = new ShortUniqueId(); uid.seq();

    -
  • Set the counter to a specific value.

    -

    Parameters

    • counter: number

    Returns void

  • Generates a UUID with a timestamp that can be extracted using uid.parseStamp(stampString);.

    +
  • Set the counter to a specific value.

    +

    Parameters

    • counter: number

    Returns void

  • Generates a UUID with a timestamp that can be extracted using uid.parseStamp(stampString);.

     const uidWithTimestamp = uid.stamp(32);
    console.log(uidWithTimestamp);
    // GDa608f973aRCHLXQYPTbKDbjDeVsSb3

    console.log(uid.parseStamp(uidWithTimestamp));
    // 2021-05-03T06:24:58.000Z
    -

    Parameters

    • finalLength: number
    • Optional date: Date

    Returns string

  • Calculate a "uniqueness" score (from 0 to 1) of UUIDs based on size of +

    Parameters

    • finalLength: number
    • Optional date: Date

    Returns string

  • Calculate a "uniqueness" score (from 0 to 1) of UUIDs based on size of dictionary and chosen UUID length.

    Given that:

      @@ -115,8 +115,8 @@

      (Useful if you need a value to rate the "quality" of the combination of given dictionary and UUID length. The closer to 1, higher the uniqueness and thus better the quality.)

      -

    Parameters

    • rounds: number = ...

    Returns number

  • Validate given UID contains only characters from the instanced dictionary or optionally provided dictionary.

    -

    Parameters

    Returns boolean

\ No newline at end of file diff --git a/docs/index.html b/docs/index.html index 064af9a..f352d7f 100644 --- a/docs/index.html +++ b/docs/index.html @@ -1,4 +1,4 @@ -short-unique-id - v5.1.1

short-unique-id - v5.1.1

Short Unique ID (UUID) Generating Library

Tests +short-unique-id - v5.2.0

short-unique-id - v5.2.0

Short Unique ID (UUID) Generating Library

Tests Try short-unique-id on RunKit NPM Downloads JsDelivr Hits

@@ -139,7 +139,7 @@

Random Color generator

const timestamp = new Date('4-01-29T03:21:21.000Z');
const result = uid.formattedUUID('Time: $t0 ID: $s2-$r4', timestamp); // timestamp is optional

console.log(result);
// Time: 63d5e631 ID: 0b-aaab

Ability to validate UUIDs against the instance dictionary or a provided dictionary

Example of using .validate() method:

-
// Instantiate using one of the default dictionary strings
const uid = new ShortUniqueId({
dictionary: 'hex',
});

const uuid = uid.stamp(32); // Generate a UUID

// Validate the generated UUID against the instance dictionary
const isValid = uid.validate(uuid);

console.log(`Is the UUID valid? ${isValid}`);

// -----------

// Validate the generated UUID against the provided dictionary
const customDictionary = ['a', 'b', /* ... */];
const isValid = uid.validate(uuid, customDictionary);

console.log(`Is the UUID valid? ${isValid}`); +
// Instantiate using one of the default dictionary strings
const uid = new ShortUniqueId({
dictionary: 'hex',
});

const uuid = uid.stamp(32); // Generate a UUID

// Validate the generated UUID against the instance dictionary
const isValid = uid.validate(uuid);

console.log(`Is the UUID valid? ${isValid}`);

// ---

// Validate the generated UUID against the provided dictionary
const customDictionary = ['a', 'b', /* ... */];
const isValid = uid.validate(uuid, customDictionary);

console.log(`Is the UUID valid? ${isValid}`);

Use in CLI

$ npm install --global short-unique-id

$ suid -h

# Usage:
# node short-unique-id [OPTION]
#
# Options:
# -l, --length=ARG character length of the uid to generate.
# -s, --stamp include timestamp in uid (must be used with --length (-l) of 10 or more).
# -t, --timestamp=ARG custom timestamp to parse (must be used along with -s, --stamp, -f, or --format).
# -f, --format=ARG string representing custom format to generate id with.
# -p, --parse=ARG extract timestamp from stamped uid (ARG).
# -d, --dictionaryJson=ARG json file with dictionary array.
# -h, --help display this help
@@ -241,7 +241,7 @@

Random Color generator

License

Copyright (c) 2018-2024 Short Unique ID Contributors.
Licensed under the Apache License 2.0.

-
\ No newline at end of file diff --git a/docs/interfaces/ShortUniqueIdOptions.html b/docs/interfaces/ShortUniqueIdOptions.html index 4db9f13..c7a4ccd 100644 --- a/docs/interfaces/ShortUniqueIdOptions.html +++ b/docs/interfaces/ShortUniqueIdOptions.html @@ -1,17 +1,17 @@ -ShortUniqueIdOptions | short-unique-id - v5.1.1

Interface ShortUniqueIdOptions

{
dictionary: ['z', 'a', 'p', 'h', 'o', 'd', ...],
shuffle: false,
debug: false,
length: 6,
} +ShortUniqueIdOptions | short-unique-id - v5.2.0

Interface ShortUniqueIdOptions

{
dictionary: ['z', 'a', 'p', 'h', 'o', 'd', ...],
shuffle: false,
debug: false,
length: 6,
}

interface ShortUniqueIdOptions {
    counter: number;
    debug: boolean;
    dictionary: string[] | ShortUniqueIdDefaultDictionaries;
    length: number;
    shuffle: boolean;
}

Properties

interface ShortUniqueIdOptions {
    counter: number;
    debug: boolean;
    dictionary: string[] | ShortUniqueIdDefaultDictionaries;
    length: number;
    shuffle: boolean;
}

Properties

counter: number

From 0 to infinity, the current value for the sequential UUID counter

-
debug: boolean

If true the instance will console.log useful info

-
dictionary: string[] | ShortUniqueIdDefaultDictionaries

User-defined character dictionary

-
length: number

From 1 to infinity, the length you wish your UUID to be

-
shuffle: boolean

If true, sequentialUUID use the dictionary in the given order

-
\ No newline at end of file diff --git a/docs/interfaces/ShortUniqueIdRanges.html b/docs/interfaces/ShortUniqueIdRanges.html index f2be623..421f4c6 100644 --- a/docs/interfaces/ShortUniqueIdRanges.html +++ b/docs/interfaces/ShortUniqueIdRanges.html @@ -1,4 +1,4 @@ -ShortUniqueIdRanges | short-unique-id - v5.1.1

Interface ShortUniqueIdRanges

interface ShortUniqueIdRanges {
    [k: string]: [number, number];
}

Indexable

[k: string]: [number, number]

Interface ShortUniqueIdRanges

interface ShortUniqueIdRanges {
    [k: string]: [number, number];
}

Indexable

[k: string]: [number, number]
\ No newline at end of file diff --git a/docs/interfaces/ShortUniqueIdRangesMap.html b/docs/interfaces/ShortUniqueIdRangesMap.html index 294dd02..a963726 100644 --- a/docs/interfaces/ShortUniqueIdRangesMap.html +++ b/docs/interfaces/ShortUniqueIdRangesMap.html @@ -1,4 +1,4 @@ -ShortUniqueIdRangesMap | short-unique-id - v5.1.1

Interface ShortUniqueIdRangesMap

interface ShortUniqueIdRangesMap {
    [k: string]: ShortUniqueIdRanges;
}

Indexable

[k: string]: ShortUniqueIdRanges

Interface ShortUniqueIdRangesMap

interface ShortUniqueIdRangesMap {
    [k: string]: ShortUniqueIdRanges;
}

Indexable

[k: string]: ShortUniqueIdRanges
\ No newline at end of file diff --git a/docs/modules.html b/docs/modules.html index 265f2ce..dcf2a9a 100644 --- a/docs/modules.html +++ b/docs/modules.html @@ -1,11 +1,11 @@ -short-unique-id - v5.1.1

short-unique-id - v5.1.1

Index

Classes

ShortUniqueId +short-unique-id - v5.2.0
\ No newline at end of file diff --git a/docs/types/ShortUniqueIdDefaultDictionaries.html b/docs/types/ShortUniqueIdDefaultDictionaries.html index b1f0702..9eca228 100644 --- a/docs/types/ShortUniqueIdDefaultDictionaries.html +++ b/docs/types/ShortUniqueIdDefaultDictionaries.html @@ -1,4 +1,4 @@ -ShortUniqueIdDefaultDictionaries | short-unique-id - v5.1.1

Type alias ShortUniqueIdDefaultDictionaries

ShortUniqueIdDefaultDictionaries: "number" | "alpha" | "alpha_lower" | "alpha_upper" | "alphanum" | "alphanum_lower" | "alphanum_upper" | "hex"

Type alias ShortUniqueIdDefaultDictionaries

ShortUniqueIdDefaultDictionaries: "number" | "alpha" | "alpha_lower" | "alpha_upper" | "alphanum" | "alphanum_lower" | "alphanum_upper" | "hex"
\ No newline at end of file diff --git a/docs/variables/DEFAULT_OPTIONS.html b/docs/variables/DEFAULT_OPTIONS.html index ebec5a6..ccbd876 100644 --- a/docs/variables/DEFAULT_OPTIONS.html +++ b/docs/variables/DEFAULT_OPTIONS.html @@ -1,4 +1,4 @@ -DEFAULT_OPTIONS | short-unique-id - v5.1.1

Variable DEFAULT_OPTIONSConst

DEFAULT_OPTIONS: ShortUniqueIdOptions = ...

Variable DEFAULT_OPTIONSConst

DEFAULT_OPTIONS: ShortUniqueIdOptions = ...
\ No newline at end of file diff --git a/docs/variables/DEFAULT_UUID_LENGTH.html b/docs/variables/DEFAULT_UUID_LENGTH.html index 90917fe..0d7d17e 100644 --- a/docs/variables/DEFAULT_UUID_LENGTH.html +++ b/docs/variables/DEFAULT_UUID_LENGTH.html @@ -1,11 +1,11 @@ -DEFAULT_UUID_LENGTH | short-unique-id - v5.1.1

Variable DEFAULT_UUID_LENGTHConst

DEFAULT_UUID_LENGTH: number = 6

6 was chosen as the default UUID length since for most cases +DEFAULT_UUID_LENGTH | short-unique-id - v5.2.0

Variable DEFAULT_UUID_LENGTHConst

DEFAULT_UUID_LENGTH: number = 6

6 was chosen as the default UUID length since for most cases it will be more than aptly suitable to provide millions of UUIDs with a very low probability of producing a duplicate UUID.

For example, with a dictionary including digits from 0 to 9, as well as the alphabet from a to z both in UPPER and lower case, the probability of generating a duplicate in 1,000,000 rounds is ~0.00000002, or about 1 in 50,000,000.

-
\ No newline at end of file