javascript雪花算法生成id
时间: 2023-12-07 07:05:17 浏览: 280
雪花算法生成ID , 在前端精度丢失的问题?
以下是两种JavaScript实现雪花算法生成ID的方法:
1. 使用snowflake-id插件
```javascript
import SnowflakeId from "snowflake-id";
const id = new SnowflakeId();
const guid = num => {
return id.generate();
};
```
2. 原生实现
```javascript
var Snowflake = /** @class */ (function() {
function Snowflake(workerId, datacenterId, sequence) {
this.workerId = workerId || 0;
this.datacenterId = datacenterId || 0;
this.sequence = sequence || 0;
this.lastTimestamp = -1;
}
Snowflake.prototype.nextId = function() {
var timestamp = this.timeGen();
if (timestamp < this.lastTimestamp) {
throw new Error(
"Snowflake clock moved backwards. Refusing to generate id for " +
(this.lastTimestamp - timestamp) +
" milliseconds"
);
}
if (this.lastTimestamp == timestamp) {
this.sequence = (this.sequence + 1) & Snowflake.SEQUENCE_MASK;
if (this.sequence == 0) {
timestamp = this.tilNextMillis(this.lastTimestamp);
}
} else {
this.sequence = 0;
}
this.lastTimestamp = timestamp;
var id =
((timestamp - Snowflake.TWEPOCH) << Snowflake.TIMESTAMP_LEFT_SHIFT) |
(this.datacenterId << Snowflake.DATA_CENTER_ID_SHIFT) |
(this.workerId << Snowflake.WORKER_ID_SHIFT) |
this.sequence;
return id.toString();
};
Snowflake.prototype.tilNextMillis = function(lastTimestamp) {
var timestamp = this.timeGen();
while (timestamp <= lastTimestamp) {
timestamp = this.timeGen();
}
return timestamp;
};
Snowflake.prototype.timeGen = function() {
return new Date().getTime();
};
Snowflake.TWEPOCH = 1288834974657;
Snowflake.WORKER_ID_BITS = 5;
Snowflake.DATA_CENTER_ID_BITS = 5;
Snowflake.MAX_WORKER_ID = -1 ^ (-1 << Snowflake.WORKER_ID_BITS);
Snowflake.MAX_DATA_CENTER_ID = -1 ^ (-1 << Snowflake.DATA_CENTER_ID_BITS);
Snowflake.SEQUENCE_BITS = 12;
Snowflake.WORKER_ID_SHIFT = Snowflake.SEQUENCE_BITS;
Snowflake.DATA_CENTER_ID_SHIFT = Snowflake.SEQUENCE_BITS + Snowflake.WORKER_ID_BITS;
Snowflake.TIMESTAMP_LEFT_SHIFT =
Snowflake.SEQUENCE_BITS + Snowflake.WORKER_ID_BITS + Snowflake.DATA_CENTER_ID_BITS;
Snowflake.SEQUENCE_MASK = -1 ^ (-1 << Snowflake.SEQUENCE_BITS);
return Snowflake;
})();
var snowflake = new Snowflake(1, 1, 1);
var id = snowflake.nextId();
```
阅读全文