Skip to content

Instantly share code, notes, and snippets.

@agorushkin
Created October 24, 2023 11:33
Show Gist options
  • Select an option

  • Save agorushkin/55fd37ecad57b5bb08be589541c24c2d to your computer and use it in GitHub Desktop.

Select an option

Save agorushkin/55fd37ecad57b5bb08be589541c24c2d to your computer and use it in GitHub Desktop.
Function to generate a ULID using bitwise operators.
const UINT32_RADIX = Math.pow(2, 32);
const UINT8_MAX = 0b11111111;
const ENCODING = '0123456789ABCDEFGHJKMNPQRSTVWXYZ';
export const ulid = (): string => {
const time = Date.now();
const bytes = crypto.getRandomValues(new Uint8Array(16));
const low = time % UINT32_RADIX;
const high = (time - low) / UINT32_RADIX;
let idx = -1;
bytes[++idx] = (high >>> 8) & UINT8_MAX;
bytes[++idx] = (high >>> 0) & UINT8_MAX;
bytes[++idx] = (low >>> 24) & UINT8_MAX;
bytes[++idx] = (low >>> 16) & UINT8_MAX;
bytes[++idx] = (low >>> 8) & UINT8_MAX;
bytes[++idx] = (low >>> 0) & UINT8_MAX;
let id = '';
for (const byte of bytes) id += ENCODING[byte % 32];
return id;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment