UNPKG

snowflakeid-producer

Version:

A simple and fast unique id generator for node.js. It generates unique id based on twitter's snowflake algorithm.

59 lines (51 loc) 1.83 kB
'use strict' const os = require('os') const test = require('node:test') const assert = require('node:assert/strict') // index.js builds a default generator with machineId=null, which reads network // interfaces; stub so tests run in CI/sandboxes where os.networkInterfaces() fails. const stubIfaces = { eth0: [ { family: 'IPv4', internal: false, mac: '02:00:00:00:00:01', address: '10.0.0.2' }, ], } const realNetworkInterfaces = os.networkInterfaces os.networkInterfaces = () => stubIfaces const { SnowflakeId, CustomSnowflakeId } = require('..') os.networkInterfaces = realNetworkInterfaces test('SnowflakeId.newId returns a numeric string', () => { const id = SnowflakeId.newId() assert.match(id, /^\d+$/) }) test('SnowflakeId consecutive ids are unique', () => { const a = SnowflakeId.newId() const b = SnowflakeId.newId() assert.notEqual(a, b) }) test('SnowflakeId.parseId round-trips newId', () => { const id = SnowflakeId.newId() const parsed = SnowflakeId.parseId(id) assert.ok(parsed.timestamp instanceof Date) assert.equal(typeof parsed.machineId, 'number') assert.equal(typeof parsed.sequence, 'number') }) test('SnowflakeId getFirstIdAt / getLastIdAt for a fixed UTC instant', () => { const ts = Date.UTC(2025, 0, 15, 12, 0, 0) const first = SnowflakeId.getFirstIdAt(ts) const last = SnowflakeId.getLastIdAt(ts) assert.match(first, /^\d+$/) assert.match(last, /^\d+$/) assert(BigInt(last) >= BigInt(first)) }) test('CustomSnowflakeId with explicit machine id produces ids', () => { const gen = new CustomSnowflakeId({ MachineIdBits: 10, SequenceBits: 12, MachineId: 7, FirstTimestamp: new Date('2024-01-01T00:00:00.000Z'), }) const id = gen.newId() assert.match(id, /^\d+$/) const parsed = gen.parseId(id) assert.equal(parsed.machineId, 7) })