Utilizing this TypeScript function allows me to generate distinctive identifiers for my database that are more user-friendly than UUIDs. In cases where duplicate key exceptions occur during record insertion, I handle them by retrying with a new ID.
const idChars: string = 'ABCDEFGHJKMNPQRSTUVWXYZ'
export function createUniqueID(): 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
}
This method produces IDs such as 20230506VJDMQD
.
The inclusion of a date prefix significantly aids in ensuring uniqueness, particularly when dealing with a large volume of records generated over an extended period. Furthermore, it proves advantageous for tasks like assigning customer or invoice numbers, as the date component imparts additional context beyond just uniqueness.
This approach is easily customizable to cater to any desired set of characters, and removing the date prefix is straightforward if needed.
In scenarios requiring generation of millions of IDs daily, increasing the loop count from 6 to a higher value may be considered, though eventually transitioning to using UUIDs might become preferable.
For those specifically seeking to generate 6 characters, a simplified JavaScript version is available:
const idChars = 'ABCDEFGHJKMNPQRSTUVWXYZ'
function createShortID() {
let id = ''
for (let i = 0; i < 6; i++) id += idChars[Math.floor(Math.random() * idChars.length)]
return id
}