From 2bd1b5835b85e061629c1e47d72777e3dff29035 Mon Sep 17 00:00:00 2001 From: babiabeo Date: Sun, 11 Aug 2024 16:29:26 +0700 Subject: [PATCH] fix(generate): fix incorrect rollover handling --- src/generate.ts | 26 +++++++++++++------------- 1 file changed, 13 insertions(+), 13 deletions(-) diff --git a/src/generate.ts b/src/generate.ts index b3f52a5..871a7dd 100644 --- a/src/generate.ts +++ b/src/generate.ts @@ -31,9 +31,9 @@ import { stringify } from "./_stringify.ts"; */ export function generate(timestamp?: number): string { const uuid = new Uint8Array(16); - const tm = timestamp ?? Date.now(); + const now = timestamp ?? Date.now(); const rand = crypto.getRandomValues(new Uint8Array(10)); - const seq = getSeq(tm, rand); + const [seq, tm] = getState(now, rand); // [octets 0-5]: timestamp (48 bits) uuid[0] = (tm / 0x10000000000) & 0xff; @@ -65,23 +65,23 @@ export function generate(timestamp?: number): string { } // The last time the function was called -let _lastTime = -Infinity; +let lastTime = -Infinity; // The sequence number (18 bits) -let _seq = 0; +let seq = 0; -function getSeq(now: number, rand: Uint8Array): number { - if (now > _lastTime) { - _seq = ((rand[7] & 0x03) << 16) | (rand[8] << 8) | rand[9]; - _lastTime = now; +function getState(now: number, rand: Uint8Array): [number, number] { + if (now > lastTime) { + seq = ((rand[7] & 0x03) << 16) | (rand[8] << 8) | (rand[9]); + lastTime = now; - return _seq; + return [seq, lastTime]; } - _seq = (_seq + 1) & 0x3ffff; + seq = (seq + 1) & 0x3ffff; - if (_seq === 0) { - ++_lastTime; + if (seq === 0) { + ++lastTime; } - return _seq; + return [seq, lastTime]; }