Tutorial :How does this JavaScript function create a GUID?



Question:

I came across this JavaScript function and I don't understand quite what it's doing, especially with the use of 0xF.

What does the 0xF do, exactly. It looks like a null nibble to me.

function()  {      var g = "";      for(var i = 0; i < 32; i++)          g += Math.floor(Math.random() * 0xF).toString(0xF)      return g;  }  


Solution:1

0xF == 15. It's simply hexadecimal notation.

However, that snippet is not actually creating a GUID, it's just stringing a bunch of random integers together. It's not possible to create a GUID in JavaScript, because generating one requires parameters that the VM can't access (network address, etc).


See also my answer to this question: How to create a GUID in Javascript?


Solution:2

0xF is hex notation

EDIT:

It looks like it's picking a random character 0-9 A-F 32 times


Solution:3

All it's doing is creating random number s and converting them to hex.

I just did a little investigating . . . it is taking a random number, multiplying it by 15 (0xF == 15) and then converting it to hex . . . the toString argument takes a radix. That's the same as saying 0xF.toString(10). That'll convert 0xF to decimal and return "15."


Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »