Pseudo-Random UUID Generation with mask support


There are a lot of cases where we may want to generate a pseudo-random universally unique identifier (UUID), sometimes called GUID.
I previously wrote an article on creating Pseudo Random numbers in JavaScript, which generates a uuid of length X where x is a numeric value supplied.


The problem with the above generator is that is does not allow developers the flexibility of specifying the format of the uuid as shown below:

'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxx0'

'xxxx-xxxx-xxxx-4xxx-yxxx-xxxxxxxxxxx'

'xxxxxxxx-xxxx-xxxx-yxxx-xxxxx-xxxxxx'

Above I’ve shown you 3 different uuid formats that 3 different developers wanted, so an algorithm had to be devised that allow developers the flexibility of changing the data formats.

One other thing to note about the above is the x values, which represents the values you want to be randomly generated. All other values, such as the numeric 4 or 0 are constant values that will be included in all GUID generation.


    /*
     * Returns a random string used for state
     */
    var uuid = function() {
        return genUuid('xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxx0');
    }
   
    /*
     * Returns a random string in the format of a mask
     */
    var genUuid = function(mask) {
        return mask.replace(/[xy]/g, function(c) {
                var r = Math.random()*16|0, v = c == 'x' ? r : (r&0x3|0x8);
                return v.toString(16);
            });    
    }

 NB: Adding fixed values reduces the uniqueness of the generation and hence weakens the effectiveness of the algorithm. 

Comments

Popular posts from this blog

Mocking Ajax with the JQuery Mockjax Library

JavaScript Module Pattern: 2 Forms