-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.cjs
More file actions
37 lines (30 loc) · 1.04 KB
/
index.cjs
File metadata and controls
37 lines (30 loc) · 1.04 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
// Snowflake generator (CommonJS)
const DEFAULT_EPOCH = 1420070400000n; // Discord epoch: 2015-01-01T00:00:00.000Z
function createSnowflakeGenerator({ epoch = DEFAULT_EPOCH, workerId = 0 } = {}) {
const _epoch = BigInt(epoch);
const _workerId = BigInt(workerId) & 0x3ffn; // 10 bits
let lastTimestamp = 0n;
let sequence = 0n;
return function generate() {
let now = BigInt(Date.now());
if (now === lastTimestamp) {
sequence = (sequence + 1n) & 0xfffn; // 12 bits
if (sequence === 0n) {
// Sequence overflow in the same millisecond — wait for next ms
while (now <= lastTimestamp) {
now = BigInt(Date.now());
}
}
} else {
sequence = 0n;
}
lastTimestamp = now;
const id = ((now - _epoch) << 22n) | (_workerId << 12n) | sequence;
return id.toString();
};
}
// Default generator (workerId 0)
const generate = createSnowflakeGenerator();
module.exports = generate;
module.exports.generate = generate;
module.exports.createSnowflakeGenerator = createSnowflakeGenerator;