snowflake.js 1.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940
  1. /**
  2. * Twitter Snowflake 算法
  3. */
  4. class Snowflake {
  5. constructor(machineId = 0) {
  6. this.machineId = machineId; // 机器 ID
  7. this.sequence = 0; // 序列号
  8. this.lastTimestamp = -1; // 上次时间戳
  9. }
  10. nextId() {
  11. let timestamp = Date.now();
  12. if (timestamp === this.lastTimestamp) {
  13. // 同一毫秒内生成多个 ID
  14. this.sequence = (this.sequence + 1) & 4095; // 序列号最大 4095
  15. if (this.sequence === 0) {
  16. // 序列号用尽,等待下一毫秒
  17. timestamp = this.waitNextMillis(timestamp);
  18. }
  19. } else {
  20. this.sequence = 0; // 新的一毫秒,重置序列号
  21. }
  22. this.lastTimestamp = timestamp;
  23. // 生成 ID(时间戳 + 机器 ID + 序列号)
  24. const id = (BigInt(timestamp) << 22n) | (BigInt(this.machineId) << 12n) | BigInt(this.sequence);
  25. return id.toString();
  26. }
  27. waitNextMillis(timestamp) {
  28. while (timestamp <= this.lastTimestamp) {
  29. timestamp = Date.now();
  30. }
  31. return timestamp;
  32. }
  33. }
  34. module.exports = Snowflake;