12345678910111213141516171819202122232425262728293031323334353637383940 |
- class Snowflake {
- constructor(machineId = 0) {
- this.machineId = machineId;
- this.sequence = 0;
- this.lastTimestamp = -1;
- }
- nextId() {
- let timestamp = Date.now();
- if (timestamp === this.lastTimestamp) {
-
- this.sequence = (this.sequence + 1) & 4095;
- if (this.sequence === 0) {
-
- timestamp = this.waitNextMillis(timestamp);
- }
- } else {
- this.sequence = 0;
- }
- this.lastTimestamp = timestamp;
-
- const id = (BigInt(timestamp) << 22n) | (BigInt(this.machineId) << 12n) | BigInt(this.sequence);
- return id.toString();
- }
- waitNextMillis(timestamp) {
- while (timestamp <= this.lastTimestamp) {
- timestamp = Date.now();
- }
- return timestamp;
- }
- }
- module.exports = Snowflake;
|