Skip to content

Instantly share code, notes, and snippets.

@catdevnull
Created April 15, 2025 02:59
Show Gist options
  • Save catdevnull/197571607e171b51a4526c49eafc75c9 to your computer and use it in GitHub Desktop.
Save catdevnull/197571607e171b51a4526c49eafc75c9 to your computer and use it in GitHub Desktop.
twitter snowflake id calc
/**
* Parses a Snowflake ID and returns its components.
* @param {string|number} snowflakeId The Snowflake ID to parse.
* @param {number} epoch The epoch to use for timestamp calculation.
* Defaults to Twitter's epoch (1288834974657).
* @returns {object} An object containing the parsed components.
*/
function parseSnowflake(snowflakeId, epoch = 1288834974657) {
const id = BigInt(snowflakeId);
const timestampBits = 41n;
const machineIdBits = 10n;
const sequenceBits = 12n;
const maxTimestamp = (1n << timestampBits) - 1n;
const maxMachineId = (1n << machineIdBits) - 1n;
const maxSequence = (1n << sequenceBits) - 1n;
const timestampShift = machineIdBits + sequenceBits;
const machineIdShift = sequenceBits;
const timestamp = Number((id >> timestampShift) + BigInt(epoch));
const machineId = Number((id >> machineIdShift) & maxMachineId);
const sequence = Number(id & maxSequence);
const date = new Date(timestamp);
return {
id: String(id),
timestamp: timestamp,
date: date.toISOString(),
machineId: machineId,
sequence: sequence,
};
}
/**
* Prints the components of a parsed Snowflake ID to the console.
* @param {object} snowflakeData The object returned by parseSnowflake.
*/
function printSnowflake(snowflakeData) {
console.log("Snowflake ID:", snowflakeData.id);
console.log("Timestamp:", snowflakeData.timestamp);
console.log("Date (UTC):", snowflakeData.date);
console.log("Machine ID:", snowflakeData.machineId);
console.log("Sequence:", snowflakeData.sequence);
}
// Example Usage:
const snowflakeId = "1541815603606036480"; // Example from the Wikipedia article
const parsedSnowflake = parseSnowflake(snowflakeId);
printSnowflake(parsedSnowflake);
printSnowflake(parseSnowflake(process.argv[2]))
// // Example with Discord epoch
// const discordSnowflakeId = "297017379053946880";
// const discordEpoch = 1420070400000; // Discord Epoch: 2015-01-01T00:00:00.000Z
// const parsedDiscordSnowflake = parseSnowflake(discordSnowflakeId, discordEpoch);
// printSnowflake(parsedDiscordSnowflake);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment