综合办公系统
您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  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. this.workerId = BigInt(_workerId);
  26. this.dataCenterId = BigInt(_dataCenterId);
  27. this.sequence = BigInt(_sequence);
  28. }
  29. Snowflake.prototype.tilNextMillis = function(lastTimestamp) {
  30. var timestamp = this.timeGen();
  31. while (timestamp <= lastTimestamp) {
  32. timestamp = this.timeGen();
  33. }
  34. return BigInt(timestamp);
  35. };
  36. Snowflake.prototype.timeGen = function() {
  37. return BigInt(Date.now());
  38. };
  39. Snowflake.prototype.nextId = function() {
  40. var timestamp = this.timeGen();
  41. if (timestamp < this.lastTimestamp) {
  42. throw new Error('Clock moved backwards. Refusing to generate id for ' +
  43. (this.lastTimestamp - timestamp));
  44. }
  45. if (this.lastTimestamp === timestamp) {
  46. this.sequence = (this.sequence + 1n) & this.sequenceMask;
  47. if (this.sequence === 0n) {
  48. timestamp = this.tilNextMillis(this.lastTimestamp);
  49. }
  50. } else {
  51. this.sequence = 0n;
  52. }
  53. this.lastTimestamp = timestamp;
  54. return ((timestamp - this.twepoch) << this.timestampLeftShift) |
  55. (this.dataCenterId << this.dataCenterIdShift) |
  56. (this.workerId << this.workerIdShift) |
  57. this.sequence;
  58. };
  59. return Snowflake;
  60. }());