|
@@ -0,0 +1,61 @@
|
|
1
|
+export var Snowflake = /** @class */ (function() {
|
|
2
|
+ function Snowflake(_workerId, _dataCenterId, _sequence) {
|
|
3
|
+ this.twepoch = 1288834974657n;
|
|
4
|
+ //this.twepoch = 0n;
|
|
5
|
+ this.workerIdBits = 5n;
|
|
6
|
+ this.dataCenterIdBits = 5n;
|
|
7
|
+ this.maxWrokerId = -1n ^ (-1n << this.workerIdBits); // 值为:31
|
|
8
|
+ this.maxDataCenterId = -1n ^ (-1n << this.dataCenterIdBits); // 值为:31
|
|
9
|
+ this.sequenceBits = 12n;
|
|
10
|
+ this.workerIdShift = this.sequenceBits; // 值为:12
|
|
11
|
+ this.dataCenterIdShift = this.sequenceBits + this.workerIdBits; // 值为:17
|
|
12
|
+ this.timestampLeftShift = this.sequenceBits + this.workerIdBits + this.dataCenterIdBits; // 值为:22
|
|
13
|
+ this.sequenceMask = -1n ^ (-1n << this.sequenceBits); // 值为:4095
|
|
14
|
+ this.lastTimestamp = -1n;
|
|
15
|
+ //设置默认值,从环境变量取
|
|
16
|
+ this.workerId = 1n;
|
|
17
|
+ this.dataCenterId = 1n;
|
|
18
|
+ this.sequence = 0n;
|
|
19
|
+ if (this.workerId > this.maxWrokerId || this.workerId < 0) {
|
|
20
|
+ throw new Error('_workerId must max than 0 and small than maxWrokerId-[' + this.maxWrokerId + ']');
|
|
21
|
+ }
|
|
22
|
+ if (this.dataCenterId > this.maxDataCenterId || this.dataCenterId < 0) {
|
|
23
|
+ throw new Error('_dataCenterId must max than 0 and small than maxDataCenterId-[' + this.maxDataCenterId + ']');
|
|
24
|
+ }
|
|
25
|
+
|
|
26
|
+ this.workerId = BigInt(_workerId);
|
|
27
|
+ this.dataCenterId = BigInt(_dataCenterId);
|
|
28
|
+ this.sequence = BigInt(_sequence);
|
|
29
|
+ }
|
|
30
|
+ Snowflake.prototype.tilNextMillis = function(lastTimestamp) {
|
|
31
|
+ var timestamp = this.timeGen();
|
|
32
|
+ while (timestamp <= lastTimestamp) {
|
|
33
|
+ timestamp = this.timeGen();
|
|
34
|
+ }
|
|
35
|
+ return BigInt(timestamp);
|
|
36
|
+ };
|
|
37
|
+ Snowflake.prototype.timeGen = function() {
|
|
38
|
+ return BigInt(Date.now());
|
|
39
|
+ };
|
|
40
|
+ Snowflake.prototype.nextId = function() {
|
|
41
|
+ var timestamp = this.timeGen();
|
|
42
|
+ if (timestamp < this.lastTimestamp) {
|
|
43
|
+ throw new Error('Clock moved backwards. Refusing to generate id for ' +
|
|
44
|
+ (this.lastTimestamp - timestamp));
|
|
45
|
+ }
|
|
46
|
+ if (this.lastTimestamp === timestamp) {
|
|
47
|
+ this.sequence = (this.sequence + 1n) & this.sequenceMask;
|
|
48
|
+ if (this.sequence === 0n) {
|
|
49
|
+ timestamp = this.tilNextMillis(this.lastTimestamp);
|
|
50
|
+ }
|
|
51
|
+ } else {
|
|
52
|
+ this.sequence = 0n;
|
|
53
|
+ }
|
|
54
|
+ this.lastTimestamp = timestamp;
|
|
55
|
+ return ((timestamp - this.twepoch) << this.timestampLeftShift) |
|
|
56
|
+ (this.dataCenterId << this.dataCenterIdShift) |
|
|
57
|
+ (this.workerId << this.workerIdShift) |
|
|
58
|
+ this.sequence;
|
|
59
|
+ };
|
|
60
|
+ return Snowflake;
|
|
61
|
+}());
|