This commit is contained in:
Sebastian Korotkiewicz 2024-02-06 06:10:46 +01:00
parent 54b9ab6559
commit 6d78355cec
Signed by: skorotkiewicz
GPG key ID: 5BDC557B496BDB0D
3 changed files with 65 additions and 75 deletions

View file

@ -1,28 +1,23 @@
function decodeSnowflake(idStr) {
const id = BigInt(idStr);
const binary = id.toString(2).padStart(64, '0');
const id = BigInt(idStr);
const timestampShift = 22n;
const machineIdShift = 12n;
const sequenceMask = 0xfffn;
const timestampShift = 22n;
const machineIdShift = 12n;
const sequenceMask = 0xFFFn; // 12 bitów na sekwencję
const timestamp = (id >> timestampShift) & 0x1ffffffffffn; // Adjusting the shift
const machineId = (id >> machineIdShift) & 0x3ffn;
const sequence = id & sequenceMask;
const timestamp = (id >> (timestampShift + machineIdShift)) & 0x1FFFFFFFFFFn;
const machineId = (id >> machineIdShift) & 0x3FFn; // 10 bitów na ID maszyny
const sequence = id & sequenceMask;
const date = new Date(Number(timestamp)); // Converting BigInt to Number, then to Date
// Upewnij się, że epoka jest taka sama, jak użyta do generowania Snowflake IDs
const epoch = BigInt(1288834974657); // Powinna być taka sama, jak w generatorze
const date = new Date(Number(epoch + (timestamp * 1000n)));
return {
timestamp: date,
machineId: machineId.toString(),
sequence: sequence.toString(),
};
return {
timestamp: date.toISOString(),
machineId: machineId.toString(),
sequence: sequence.toString(),
};
}
// Użycie
const idStr = '7160488856901390336'; // Przykładowy identyfikator Snowflake
// Use
const idStr = "7160488856901390336";
const decoded = decodeSnowflake(idStr);
console.log(decoded);