0

I am quite new to JS and was going over the code for generating a GUID / UUID.

This is the code I found in this Stackoverflow question

function uuidv4() {
  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);
  });
}

console.log(uuidv4());

What I am having trouble with is understanding this syntax:

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

Can someone help me by explaining step by step what it does?

Your support is much appreciated.

Regards

1 Answers1

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

is the same as

var r = Math.random() * 16 | 0;

ie, create a random number in the range from 0-15 (or 0-f in hex) without decimal places. You could also write this line as

var r = Math.floor(Math.random() * 16) 

but | 0 is probably faster ... And

var v = c == 'x' ? r : (r & 0x3 | 0x8);

ie, depending on the value of the current character to replace (ie 'x' or 'y') use either r or r | 0x3 | 0x8 as value for the current place. The latter is because of specification of UUID version 4, that certain bits must have certain values. See specs for details.

You can rewrite this line as follows

var v = 0;
if (c == 'x') v = r;
else v = r & 0x3 | 0x8 

So v is still a value between 0 and 15, which is than converted to a hex char (0 - f) with v.toString(16)

Community
  • 1
  • 1
derpirscher
  • 14,418
  • 3
  • 18
  • 35
  • Thank you very much! I got it with your explanation. I was having trouble at the end with the logic behing this part (r & 0x3 | 0x8). Turns out the character "y" in the UUID (version 4) must only be one of the following values (8,9,a or b) nothing more. As for the rest very clear! – Santiago Sierra Jan 24 '21 at 21:47