snowflakify
Version:
The most complete Snowflake ID generator in TypeScript
102 lines (100 loc) • 2.68 kB
TypeScript
import { FragmentArray, SnowflakifyOptions, DestructuredFragment } from './@types';
/**
* Snowflakify class for generating snowflake IDs.
* @public
*/
export default class Snowflakify {
/**
* Total number of bits in the snowflake ID.
* @readonly
*/
readonly totalBits: number;
/**
* Array of fragments used to generate snowflake IDs.
*
* @remarks
* When reading this array outside of a Snowflakify class:
* - Do not call fragments methods.
* - Do not add or remove fragments.
* - Do not reorder fragments.
* - Do not modify this array.
*
* @readonly
*/
readonly fragments: FragmentArray;
private buffer;
/**
*
* @remarks
* A Snowflakify instance must follow the following conditions:
* - At least one TimestampFragment or RandomFragment.
* - A RandomFragment must be coupled with at least one TimestampFragment or SequenceFragment.
*
* @param options - Optional parameter for specifying Snowflakify options.
*
* Can be an array of fragments or an object with the following properties:
* - `epoch`: A custom epoch timestamp.
* - `preset`: `"worker_process"`, `"ipv4"`, or `"mac"`
*/
constructor(options?: SnowflakifyOptions);
/**
* Returns a snowflake ID.
*
* @returns The sum of all fragments values shifted to the left by their bitShift.
*
* @public
*/
nextId(): bigint;
/**
* Returns a destructured snowflake.
*
* @param snowflake - The snowflake to be destructured.
*
* @returns An array of destructured fragments.
*
* @throws `[SNOWFLAKE_INVALID]` If snowflake is not a number, bigint, or string of a positive number.
*
* @public
*/
destructure(snowflake: number | bigint | string): DestructuredFragment[];
/**
* Returns a snowflake ID as Hexadecimal.
*
* @returns a snowflake ID converted to Hexadecimal
*
* @public
*/
nextHexId(): string;
/**
* Returns a destructured snowflake.
*
* @param snowflake - The hexadecimal snowflake to be destructured.
*
* @returns An array of destructured fragments.
*
* @throws `[SNOWFLAKE_INVALID]` If snowflake is not a valid hexademical string.
*
* @public
*/
destructureHex(snowflake: string): DestructuredFragment[];
/**
* Returns the buffers content.
*
* @returns An array of snowflake IDs or undefined if the buffer is not instatiated.
*
* @public
*/
getBuffer(): BigInt64Array | undefined;
/**
* @internal
*/
private updateBitShiftsAndMasks;
/**
* @internal
*/
private coupleTimestampAndSequence;
/**
* @internal
*/
private resolveOptions;
}