Skip to content

Commit dcb391a

Browse files
steffenaggerdurran
authored andcommitted
Lazy loading PROCESS_UNIQUE for ObjectId
1 parent f34cabc commit dcb391a

File tree

1 file changed

+8
-3
lines changed

1 file changed

+8
-3
lines changed

src/objectid.ts

Lines changed: 8 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -2,9 +2,6 @@ import { Buffer } from 'buffer';
22
import { ensureBuffer } from './ensure_buffer';
33
import { deprecate, isUint8Array, randomBytes } from './parser/utils';
44

5-
// constants
6-
const PROCESS_UNIQUE = randomBytes(5);
7-
85
// Regular expression that checks for hex value
96
const checkForHexRegExp = new RegExp('^[0-9a-fA-F]{24}$');
107

@@ -20,6 +17,9 @@ let i = 0;
2017
while (i < 10) decodeLookup[0x30 + i] = i++;
2118
while (i < 16) decodeLookup[0x41 - 10 + i] = decodeLookup[0x61 - 10 + i] = i++;
2219

20+
// Unique sequence for the current process (initialized on first use)
21+
let PROCESS_UNIQUE: Uint8Array | null = null;
22+
2323
/** @public */
2424
export interface ObjectIdLike {
2525
id: string | Buffer;
@@ -176,6 +176,11 @@ export class ObjectId {
176176
// 4-byte timestamp
177177
buffer.writeUInt32BE(time, 0);
178178

179+
// set PROCESS_UNIQUE if yet not initialized
180+
if (PROCESS_UNIQUE === null) {
181+
PROCESS_UNIQUE = randomBytes(5);
182+
}
183+
179184
// 5-byte process unique
180185
buffer[4] = PROCESS_UNIQUE[0];
181186
buffer[5] = PROCESS_UNIQUE[1];

0 commit comments

Comments
 (0)