A universally-unique, lexicographically-sortable, identifier generator
78
Core functionality for generating ULIDs with support for both simple generation and monotonic factories that ensure lexicographic ordering within the same millisecond.
Generates a single ULID with optional custom timestamp and PRNG.
/**
* Generate a ULID
* @param seedTime - Optional time seed (default: Date.now())
* @param prng - Optional PRNG function (default: auto-detected)
* @returns A ULID string
*/
function ulid(seedTime?: number, prng?: PRNG): ULID;Usage Examples:
import { ulid } from "ulid";
// Generate with current timestamp
const id1 = ulid(); // "01HNZXD07M5CEN5XA66EMZSRZW"
// Generate with specific timestamp
const customTime = Date.now();
const id2 = ulid(customTime); // "01HNZXD07M5CEN5XA66EMZSRZ0"
// Generate with custom PRNG
const customPrng = () => Math.random();
const id3 = ulid(undefined, customPrng);Creates a factory function that generates monotonically increasing ULIDs within the same millisecond, ensuring proper lexicographic ordering.
/**
* Create a ULID factory to generate monotonically-increasing ULIDs
* @param prng - Optional PRNG to use (default: auto-detected)
* @returns A ULID factory function
*/
function monotonicFactory(prng?: PRNG): ULIDFactory;
/**
* ULID factory function type
* @param seedTime - Optional time seed (default: Date.now())
* @returns A ULID string
*/
type ULIDFactory = (seedTime?: number) => ULID;Usage Examples:
import { monotonicFactory } from "ulid";
// Create a monotonic factory
const factory = monotonicFactory();
// Generate ordered ULIDs within the same millisecond
const id1 = factory(); // "01HNZXD07M5CEN5XA66EMZSRZA"
const id2 = factory(); // "01HNZXD07M5CEN5XA66EMZSRZB"
const id3 = factory(); // "01HNZXD07M5CEN5XA66EMZSRZC"
// Use with specific timestamp
const timestamp = Date.now();
const id4 = factory(timestamp);
const id5 = factory(timestamp); // Will increment random portion
// Create factory with custom PRNG
const customFactory = monotonicFactory(() => 0.5);Monotonic Behavior:
When multiple ULIDs are generated with the same timestamp (either explicitly or within the same millisecond), the monotonic factory ensures lexicographic ordering by:
Pseudo-random number generator function type used throughout the library.
/**
* Pseudo-random number generator function
* Should return a number between 0 (inclusive) and 1 (exclusive)
*/
type PRNG = () => number;The library automatically detects the best available PRNG in the current environment:
crypto.getRandomValues() or msCrypto.getRandomValues()crypto.randomBytes()self.crypto.getRandomValues()type ULID = string;
type ULIDFactory = (seedTime?: number) => ULID;
type PRNG = () => number;Install with Tessl CLI
npx tessl i tessl/npm-ulidevals
scenario-1
scenario-2
scenario-3
scenario-4
scenario-5
scenario-6
scenario-7
scenario-8
scenario-9
scenario-10