short-unique-id

repository·main·Indexed 19 days ago

https://github.com/simplyhexagonal/short-unique-id

A lightweight, no-dependency library for generating random or sequential UUIDs of any length with low collision probabilities. Version 5.3.2 supports custom dictionaries, timestamp embedding via stamp() and parseStamp(), and custom formatting. It includes a CLI for ID generation and tools to analyze collision probability and uniqueness.

Tokens
3.8K
Snippets
19
Records
21
Agent score
66%

What's inside short-unique-id

  1. Install and use ShortUniqueId as a module

    main

    You can integrate short-unique-id into your project using various environments:

    Node.js / TypeScript

    import ShortUniqueId from 'short-unique-id';
    // or
    const ShortUniqueId = require('short-unique-id');

    Deno

    import ShortUniqueId from 'https://esm.sh/short-unique-id';

    Browser

    Add the minified script via CDN:

    <script src="https://cdn.jsdelivr.net/npm/short-unique-id@latest/dist/short-unique-id.min.js"></script>
    import ShortUniqueId from 'short-unique-id';
  2. Use the short-unique-id CLI

    main

    The short-unique-id CLI allows you to generate unique IDs directly from your terminal. You can control the length of the ID, include timestamps, use custom formats, or parse timestamps from existing stamped IDs.

    Basic usage:

    node short-unique-id [OPTION]
    # Example: Generate a random ID
    node short-unique-id
    
    # Example: Generate an ID with length 15
    node short-unique-id -l 15
  3. Initialize ShortUniqueId

    main

    To use the library, import the ShortUniqueId class and instantiate it. You can pass an optional ShortUniqueIdOptions object to customize the behavior, such as the character dictionary, length, and whether to shuffle the dictionary.

    // ES6 / TypeScript Import
    import ShortUniqueId from 'short-unique-id';
    
    // Instantiate with default options
    const uid = new ShortUniqueId();
    
    // Instantiate with custom options
    const uid = new ShortUniqueId({
      dictionary: ['a', 'b', 'c'],
      length: 10,
      shuffle: true
    });
  4. Generate and parse UUIDs with timestamps

    main

    The library allows you to include a timestamp in a UUID, which can later be extracted.

    • Use stamp(length) to generate a UUID containing a timestamp. Note that when using --stamp in the CLI, the length must be 10 or more.
    • Use parseStamp(uuid) to recover the ISO timestamp from a stamped UUID.

    CLI Usage:

    • -s, --stamp: Include timestamp (requires -l of 10+).
    • -p, --parse=ARG: Extract timestamp from a stamped UUID.
    const uid = new ShortUniqueId();
    
    const uidWithTimestamp = uid.stamp(32);
    console.log(uidWithTimestamp);
    
    const recoveredTimestamp = uid.parseStamp(uidWithTimestamp);
    console.log(recoveredTimestamp); // e.g., 2021-05-03T06:24:58.000Z
  5. Generate random and sequential UUIDs

    main

    After instantiating ShortUniqueId, you can generate unique IDs using the following methods:

    • rnd(): Generates a random UUID.
    • seq(): Generates a sequential UUID.

    You can also use destructuring to access randomUUID and sequentialUUID directly. The library uses .bind() on these methods to ensure they respect the options provided during instantiation.

    Note for v5+ users: You can no longer call the instance as a function (e.g., uid()). You must use uid.rnd() instead.

    const uid = new ShortUniqueId({ length: 10 });
    uid.rnd(); // e.g., p0ZoB1FwH6
    
    // Or via destructuring
    const { randomUUID, sequentialUUID } = new ShortUniqueId({ length: 10 });
    console.log(randomUUID());
    console.log(sequentialUUID());
  6. Configure dictionaries and custom formatting

    main

    Default Dictionaries

    You can specify a dictionary during instantiation or change it later using setDictionary(). Available default strings include:

    • alphanum (default)
    • number
    • alpha
    • alpha_lower
    • alpha_upper
    • alphanum_lower
    • alphanum_upper
    • hex

    Custom Formatting

    Use formattedUUID(format, [timestamp]) to create custom patterns. Use the following tokens:

    • $r: random UUID
    • $s: sequential UUID
    • $t: timestamp UUID
    // Using a specific dictionary
    const uid = new ShortUniqueId({ dictionary: 'hex' });
    
    // Changing dictionary after instantiation
    uid.setDictionary('alpha_upper');
    
    // Custom formatting
    const timestamp = new Date('2029-04-01T03:21:21.000Z');
    const result = uid.formattedUUID('Time: $t0 ID: $s2-$r4', timestamp);
    console.log(result); // e.g., "Time: 63d5e631 ID: 0b-aaab"
  7. Validate UUIDs against a dictionary

    main

    You can verify if a UUID is valid by checking it against the instance's current dictionary or a custom provided dictionary using the validate(uuid, [customDictionary]) method.

    const uid = new ShortUniqueId({ dictionary: 'hex' });
    const uuid = uid.stamp(32);
    
    // Validate against instance dictionary
    const isValid = uid.validate(uuid);
    
    // Validate against a custom dictionary
    const customDictionary = ['a', 'b', 'c'];
    const isValidCustom = uid.validate(uuid, customDictionary);
  8. Configure a custom dictionary via CLI

    main

    You can use a custom character set by providing a path to a JSON file using the --dictionaryJson (-d) flag.

    Requirements for the JSON file:

    • It must be a valid JSON file.
    • It must contain a single array.
    • The array must contain two or more elements.
    • Every element in the array must be a single-character string.

    Example JSON structure:

    ["a", "b", "c", "d"]
    node short-unique-id -d ./my-custom-dictionary.json
  9. Configure ShortUniqueIdOptions

    main

    When instantiating ShortUniqueId, you can provide a ShortUniqueIdOptions object:

    KeyTypeDescription
    dictionarystring[] or ShortUniqueIdDefaultDictionariesUser-defined character dictionary. Default is 'alphanum'.
    shufflebooleanIf true, the dictionary is shuffled. For sequential UUIDs, false uses the dictionary in the given order.
    debugbooleanIf true, the instance will console.log useful info.
    lengthnumberThe desired length of the UUID. Default is 6.
    counternumberThe starting value for the sequential UUID counter.

    Default Dictionaries:

    • 'number'
    • 'alpha'
    • 'alpha_lower'
    • 'alpha_upper'
    • 'alphanum'
    • 'alphanum_lower'
    • 'alphanum_upper'
    • 'hex'
  10. Use ShortUniqueId via CLI

    main

    After installing globally via npm install --global short-unique-id, you can use the suid command.

    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, -f, or -p).
    • -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.
    # Generate a stamped UUID of length 42
    $ suid -s -l 42
    
    # Parse a timestamp from a UUID
    $ suid -p lW611f30a2ky4276g3l8N7nBHI5AQ5rCiwYzU47HP2
  11. Analyze UUID uniqueness and collision probability

    main

    The library provides methods to mathematically evaluate the quality and collision risk of your chosen configuration:

    • availableUUIDs(length): Returns the total number of possible unique UUIDs for a given length.
    • approxMaxBeforeCollision(rounds): Returns the approximate number of generations possible before a collision is expected (based on the Birthday Problem).
    • collisionProbability(rounds, length): Returns the probability of a collision occurring within a specific number of generation rounds.
    • uniqueness(rounds): Returns a score from 0 to 1 representing the 'uniqueness' quality of the combination.
    const uid = new ShortUniqueId({ length: 10 });
    
    const total = uid.availableUUIDs();
    const prob = uid.collisionProbability(1000000); // Prob in 1M rounds
    const score = uid.uniqueness();
    
    console.log(`Total: ${total}, Prob: ${prob}, Score: ${score}`);
  12. Use the ShortUniqueId class

    main

    The ShortUniqueId class is the primary entry point for generating short, unique IDs. It extends the core functionality and is exported as the main module. You can instantiate it with custom options to control the length, character sets (dictionaries), and ranges of the generated IDs.

    import ShortUniqueId from 'short-unique-id';
    
    const uid = new ShortUniqueId({ length: 10 });
    const id = uid.random();