Nodejs generate short unique alphanumeric

前端 未结 6 656
借酒劲吻你
借酒劲吻你 2021-01-30 23:55

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 the

6条回答
  •  攒了一身酷
    2021-01-31 00:49

    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.

提交回复
热议问题