I use this TypeScript function to create unique identifiers in my database that are much more readable than UUIDs. Note that when inserting records I catch the duplicate key exception and retry with a new ID.
const idChars: string = 'ABCDEFGHJKMNPQRSTUVWXYZ'
export function generateId(): string {
const now: Date = new Date()
let id = now.getUTCFullYear().toString()
id += now.getUTCMonth().toString().padStart(2, '0')
id += now.getUTCDay().toString().padStart(2, '0')
for (let i = 0; i < 6; i++) id += idChars[Math.floor(Math.random() * idChars.length)]
return id
}
It generates ids like 20230506VJDMQD
.
The date prefix helps a lot with uniqueness, especially if you create thousands of records in the database over a long period of time. It's also super helpful for things like customer numbers or invoice numbers, where the date part provides additional information, not just uniqueness.
It's very easy to adapt this to any set of characters you prefer, and if you don't want the date prefix it's easy to remove that part from the code.
If you need to make millions of IDs per day, then you could increase the loop count from 6 to a bigger number, but at some point you might as well just use UUIDs.
If you really want just 6 characters, then the simplified version in JavaScript is
const idChars = 'ABCDEFGHJKMNPQRSTUVWXYZ'
function generateId() {
let id = ''
for (let i = 0; i < 6; i++) id += idChars[Math.floor(Math.random() * idChars.length)]
return id
}