-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.ts
38 lines (31 loc) · 1.04 KB
/
index.ts
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
export class Snowflake {
seq: number;
nodeId: number;
epoch: number;
constructor(opts: {nodeId: number}) {
opts = opts || {nodeId: 1023};
this.seq = 0;
this.nodeId = opts.nodeId;
this.epoch = 1562544000000;
}
gen = (timestamp = Date.now()): string => {
if (this.seq >= 4095) this.seq = 0;
const binary = `${(timestamp - this.epoch).toString(2).padStart(42, '0')}${(this.nodeId >>> 0).toString(2)}${(this.seq++).toString(2).padStart(12, '0')}`;
return this.binaryToID(binary);
}
private binaryToID(num: string): string {
let dec = '';
while (num.length > 50) {
const high = parseInt(num.slice(0, -32), 2);
const low = parseInt((high % 10).toString(2) + num.slice(-32), 2);
dec = (low % 10).toString() + dec;
num = Math.floor(high / 10).toString(2) + Math.floor(low / 10).toString(2).padStart(32, '0');
}
let num2: number = parseInt(num, 2);
while (num2 > 0) {
dec = (num2 % 10).toString() + dec;
num2 = Math.floor(num2 / 10);
}
return dec;
}
}