JavaScript: Creating GUID / UUID

From The Travis van der Font Wiki
Jump to: navigation, search
Basic GUID:
function guid()
{
    function s4()
    {
        return Math.floor((1 + Math.random()) * 0x10000).toString(16).substring(1);
    }
    
    return s4()+s4()+'-'+s4()+'-'+s4()+'-'+s4()+'-'+s4()+s4()+s4();
}
Such values are not genuine UUIDs as Math.random leave the chance for collision.

RFC4122 allows random ("version 4") GUIDs.

Verson 4 UUID:
function uuid_v4()
{
    return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c)
    {
        var r = Math.random() * 16 | 0,
            v = c == 'x' ? r : (r & 0x3 | 0x8);
        
        return v.toString(16);
    });
}
Version 4 UUID (using Date API):
function uuid_v4()
{
    var d =  Date.now() || new Date().getTime();

    if (typeof performance !== 'undefined' && typeof performance.now === 'function')
    {
        d += performance.now(); //use high-precision timer if available
    }
    
    return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c)
    {
        var r = (d + Math.random() * 16) % 16 | 0;
            d = Math.floor(d / 16);
             
        return (c === 'x' ? r : (r & 0x3 | 0x8)).toString(16);
    });
}
Verison 4 UUID (using ES6 - Crypto API *recommended*):
function uuid_v4()
{
    return ([1e7]+-1e3+-4e3+-8e3+-1e11).replace(/[018]/g, c => (c ^ crypto.getRandomValues(new Uint8Array(1))[0] & 15 >> c / 4).toString(16));
}