Skip to content

Instantly share code, notes, and snippets.

@xacrimon
Created November 24, 2021 18:23
Show Gist options
  • Save xacrimon/945557c4b7a9d074473431b4e3072bd2 to your computer and use it in GitHub Desktop.
Save xacrimon/945557c4b7a9d074473431b4e3072bd2 to your computer and use it in GitHub Desktop.
function generateByteHexTable(): string[] {
const table = new Array(256);
for (let i = 0; i < 256; i++) {
table[i] = (i + 0x100).toString(16).substr(1);
}
return table;
}
function generateQuadHexTable(): string[] {
const table = new Array(16);
for (let i = 0; i < 16; i++) {
table[i] = (i + 0x10).toString(16).substr(1);
}
return table;
}
const byteToHex = generateByteHexTable();
const quadToHex = generateQuadHexTable();
function randByte(): number {
return Math.floor(Math.random() * 256);
}
export function gen(shard?: number): string {
const shardValue = shard ?? 0;
const millis = Date.now();
const secs = Math.floor(millis / 1000);
const subsecs = millis % 1000;
return (
byteToHex[shardValue] +
"-" +
byteToHex[(secs >> 28) & 0xff] +
byteToHex[(secs >> 20) & 0xff] +
byteToHex[(secs >> 12) & 0xff] +
byteToHex[(secs >> 4) & 0xff] +
quadToHex[secs & 0xf] +
"-" +
quadToHex[subsecs >> 8 & 0xf] +
byteToHex[subsecs & 0xff] +
"-" +
byteToHex[randByte()] +
byteToHex[randByte()] +
byteToHex[randByte()] +
byteToHex[randByte()] +
byteToHex[randByte()] +
byteToHex[randByte()] +
byteToHex[randByte()] +
byteToHex[randByte()] +
byteToHex[randByte()]
).toLowerCase();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment