Skip to content

Instantly share code, notes, and snippets.

@elonmir
Created July 4, 2024 13:49
Show Gist options
  • Select an option

  • Save elonmir/ae267d51299edad47b8323c6d5b7ba9e to your computer and use it in GitHub Desktop.

Select an option

Save elonmir/ae267d51299edad47b8323c6d5b7ba9e to your computer and use it in GitHub Desktop.
Convert UUID to a human readable ID
import { v4 as uuidv4 } from 'uuid';
// Custom character set (26 letters + 10 digits)
const CHAR_SET = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
function uuidToCustomIid(uuidStr: string, length: number = 10): string {
// Remove dashes from UUID
const cleanUuid = uuidStr.replace(/-/g, '');
// Convert to an integer
const uuidInt = BigInt(`0x${cleanUuid}`);
// Convert the integer to a string using the custom character set
let customIid = '';
let tempInt = uuidInt;
while (tempInt > 0) {
const remainder = tempInt % BigInt(CHAR_SET.length);
customIid = CHAR_SET[Number(remainder)] + customIid;
tempInt = tempInt / BigInt(CHAR_SET.length);
}
// Ensure the result is exactly `length` characters long
return customIid.padStart(length, '0').substring(0, length);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment