Search code examples
javascriptmathrandomuuid

generate Random uuid Javascript


I'm trying to build a function to generate a random uuid, I found some thing on stack and I need to understand a little bit how that function work to create it with typescript :

public generateUniqSerial() {
    return 'xxxx-xxxx-xxx-xxxx'.replace(/[x]/g, function (c) {
      var r = Math.random() * 16 | 0, v = c == 'x' ? r : (r & 0x3 | 0x8);
      return v.toString(16);
    });
  }

is that writen good in es6 and can you help to understand how that line works :

var r = Math.random() * 16 | 0, v = c == 'x' ? r : (r & 0x3 | 0x8);

Solution

  • It just replaces every 'x' in 'xxxx-xxxx-xxx-xxxx' with a random [0123456789abcdef] hex character. A little bit more than you really need to do for a uuid. I usually do:

    Math.random().toString().replace("0.", "")