Initial commit

This commit is contained in:
Sebastian Korotkiewicz 2024-02-06 05:43:57 +01:00
commit 9bc4ca3870
Signed by: skorotkiewicz
GPG key ID: 5BDC557B496BDB0D
4 changed files with 155 additions and 0 deletions

47
encode.js Normal file
View file

@ -0,0 +1,47 @@
class Snowflake {
constructor(machineId) {
if (machineId < 0 || machineId >= 1024) {
throw new Error('Machine ID must be in the range 0-1023.');
}
this.machineId = BigInt(machineId);
this.sequence = BigInt(0);
this.lastTimestamp = BigInt(-1);
// Konfiguracja bitów: 41 bitów na czas, 10 bitów na ID maszyny, 12 bitów na sekwencję
this.timestampShift = 22n;
this.machineIdShift = 12n;
this.sequenceMask = 0xFFFn; // 4095 w dziesiętnym, BigInt
}
generate() {
let timestamp = BigInt(Date.now());
if (timestamp === this.lastTimestamp) {
this.sequence = (this.sequence + 1n) & this.sequenceMask;
if (this.sequence === 0n) {
while (timestamp <= this.lastTimestamp) {
timestamp = BigInt(Date.now());
}
}
} else {
this.sequence = 0n;
}
this.lastTimestamp = timestamp;
const id = ((timestamp & 0x1FFFFFFFFFFn) << this.timestampShift) |
(this.machineId << this.machineIdShift) |
this.sequence;
return id.toString(); // Zwraca string, ponieważ BigInt może być zbyt duży dla niektórych zastosowań
}
}
// Użycie
const machineId = 1; // ID maszyny (0-1023)
const snowflake = new Snowflake(machineId);
const id1 = snowflake.generate();
console.log(id1);