Created
July 4, 2024 13:49
-
-
Save elonmir/ae267d51299edad47b8323c6d5b7ba9e to your computer and use it in GitHub Desktop.
Convert UUID to a human readable ID
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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