UNPKG

unique-id-generator-ts

Version:

A high-performance unique ID generator based on Snowflake architecture. Supports up to 4096 unique IDs per millisecond per machine.

44 lines (43 loc) 1.61 kB
/** * UniqueIdGenerator * * A high-performance unique ID generator based on Snowflake architecture. * Generates a 64-bit numeric ID composed of: * * - 41 bits for timestamp (in milliseconds since a custom epoch) * - 10 bits for machine ID (auto-generated from OS network interface) * - 12 bits for sequence number (increments within the same millisecond) * * Features: * - Generates up to 4096 unique IDs per millisecond per machine * - Ensures time-ordered and compact identifiers * - Automatically derives a consistent machine ID using Node.js `os` module * - Includes decoding method to extract timestamp, machine ID, and sequence * * Example ID structure: * (timestamp << 22) | (machineId << 12) | sequence * * Suitable for distributed systems where unique, sortable, and compact IDs are needed. */ import { IDecodedIdResponse } from "./domain"; export declare class UniqueIdGenerator { private epoch; private machineId; private sequence; private lastTimestamp; constructor(epoch?: number); /** * Generates a unique 64-bit ID based on timestamp, machine ID, and sequence. * Returns a `bigint` ID. */ generateUniqueId(): string; /** * Decodes a 64-bit ID into timestamp, machine ID, and sequence. * @param id - The ID to decode * @param epoch - (Optional) Custom epoch used during ID generation. Defaults to the instance's epoch. * @returns An object with timestamp, machineId, and sequence */ decodeId(id: string, epoch?: number): IDecodedIdResponse; private currentTimestamp; private generateUniqueMachineId; }