ulid JavaScript

repository·master·Indexed 25 days ago

https://github.com/ulid/javascript

A JavaScript implementation of Universally Unique Lexicographically Sortable Identifiers (ULID). Version 3.0.2 provides 128-bit compatible, URL-safe, and sortable 26-character identifiers. Features include monotonic generation via monotonicFactory, ULID validation with isValid, timestamp encoding/decoding, and conversion utilities between ULID and UUID.

Tokens
1K
Snippets
6
Records
17
Agent score
36%

What's inside ulid

  1. Generate a ULID with a specific seed time

    master

    You can pass a millisecond timestamp as an argument to ulid(). This ensures the time component of the generated ULID remains consistent, which is useful for data migrations.

    ulid(1469918176385) // "01ARYZ6S41TSV4RRFFQ69G5FAV"
  2. Override the Pseudo-Random Number Generator (PRNG)

    master

    By default, ulid uses cryptographically-secure PRNGs (crypto.getRandomValues in browsers or crypto.randomBytes in Node.js). If you need to use an insecure generator like Math.random, you can pass it to monotonicFactory.

    const ulid = monotonicFactory(() => Math.random());
    
    ulid(); // "01BXAVRG61YJ5YSBRM51702F6M"
  3. Generate monotonic ULIDs

    master

    To ensure that ULIDs generated within the same millisecond maintain a strict sort order, use monotonicFactory. This increments the least-significant random bits for subsequent calls within the same timestamp, and preserves sort order even if a lower timestamp is provided later.

    import { monotonicFactory } from "ulid";
    
    const ulid = monotonicFactory();
    
    // Strict ordering for the same timestamp
    ulid(150000); // "000XAL6S41ACTAV9WEVGEMMVR8"
    ulid(150000); // "000XAL6S41ACTAV9WEVGEMMVR9"
    
    // Preserves sort order even with a lower timestamp
    ulid(100000); // "000XAL6S41ACTAV9WEVGEMMVRD"
  4. Encode and decode ULID timestamps

    master

    You can extract the timestamp from a ULID using decodeTime, or create a ULID time component string using encodeTime.

    Note: encodeTime only encodes the time portion (the first 10 characters) of a ULID, not a full 26-character ID.