teggy teggy - 4 months ago 22
Javascript Question

Nodejs generate short unique alphanumeric

I would like to generate a short unique alphanumeric value to be used as confirmation codes for online purchases. I've looking into https://github.com/broofa/node-uuid but their uuids are too long and I want to have them be around 8 characters long. What is the best way I can achieve this?

Answer

10/23/15: See the hashids answer below, as well!

You can borrow from the URL shortener model and do something like this:

(100000000000).toString(36);
// produces 19xtf1ts

(200000000000).toString(36);
// produces 2jvmu3nk

Just increment the number to keep it unique:

function(uniqueIndex) {
    return uniqueIndex.toString(36);
}

Note that this is only really useful for "single instance" services that don't mind a certain amount of predictability in the way this is ordered (via basic increment). If you need a truly unique value across a number of application / DB instances, you should really consider a more full featured option per some of the comments.

Comments