好的,下面是 JavaScript 实现的雪花算法代码:
``` // 雪花算法生成唯一ID function snowflake() { // 起始时间戳 const startTimestamp = 1420041600000;
// 机器ID占用的位数 const machineIdBits = 5; // 数据中心ID占用的位数 const datacenterIdBits = 5;
// 最大机器ID(2^5-1) const maxMachineId = -1 ^ (-1 << machineIdBits); // 最大数据中心ID(2^5-1) const maxDatacenterId = -1 ^ (-1 << datacenterIdBits);
// 毫秒内自增序列占用的位数 const sequenceBits = 12;
// 机器ID左移12位 const machineIdShift = sequenceBits; // 数据中心ID左移17位(12+5) const datacenterIdShift = sequenceBits + machineIdBits; // 时间戳左移22位(12+5+5) const timestampLeftShift = sequenceBits + machineIdBits + datacenterIdBits;
// 生成序列的掩码(2^12-1) const sequenceMask = -1 ^ (-1 << sequenceBits);
// 机器ID let machineId = Math.floor(Math.random() * (maxMachineId + 1)); // 数据中心ID let datacenterId = Math.floor(Math.random() * (maxDatacenterId + 1)); // 序列 let sequence = 0; // 上一次生成ID的时间戳 let lastTimestamp = -1;
// 获取当前时间戳 function getCurrentTimestamp() { return new Date().getTime(); }
return function generate() { let timestamp = getCurrentTimestamp(); // 如果当前时间戳小于上一次生成ID的时间戳,说明系统时钟回退过,出现问题 if (timestamp < lastTimestamp) { throw new Error(Clock moved backwards. Refusing to generate id for ${lastTimestamp - timestamp} milliseconds.
); } // 如果当前时间戳与