Reputation: 475
I'm trying to write a JavaScript GUID generator for 8 characters including lowercase / uppercase letters, numbers and symbols. I found these solutions but need an explanation on what is happening in each. Originally I thought I'd need a string holding all the letters/numbers/symbols that I would index into with random number function to build a new GUID, but these solutions seem to create numbers/letters/symbols out of thin air.
In solution 1, what is the purpose of "1+" and "0x10000"? What is the purpose of ".toString(16)" and ".substring(1)" and how is it generating numbers/symbols/AND letters with just that little bit of code?
Solution 1:
function guid() {
function s4() {
return Math.floor((1 + Math.random()) * 0x10000)
.toString(16)
.substring(1);
}
return s4() + s4() + '-' + s4() + '-' + s4() + '-' +
s4() + '-' + s4() + s4() + s4();
}
In solution 2, I see how the GUID is 32 characters long but don't understand why Math.Random is being multiplied by specifically "16", with a toString(16) attached but no ".substring(x)" this time?
Solution 2:
function generateGuid() {
var result, i, j;
result = '';
for(j=0; j<32; j++) {
if( j == 8 || j == 12|| j == 16|| j == 20)
result = result + '-';
i = Math.floor(Math.random()*16).toString(16).toUpperCase();
result = result + i;
}
return result;
}
No need to explain the structure of a GUID nor what is a hyphen is XD
Any and all detailed explanations are appreciated!
Upvotes: 1
Views: 14427
Reputation: 10458
In the 2nd case Math.random() would generate a number which lies between 0(inclusive) to 1(exclusive).
Now if I want a number which should be < 16, multiplying 16 with a value in [0, 1) should do the job for me, toString(16) converts it into a digit of base 16. We add 32 such digits overall
The 1st example generates a number between (1.0, 2.0] and multiplies it with (10^4) to the base 16. Now we have a number in the range (10000, 20000] base 16.
taking the last 4 digits should suffice for us so we take the relevant substring out of it.
That being the case I think
Math.floor((Math.random()) * 0x10000)
.toString(16)
would also suffice for that solution, since we need a 4 digit hexa number
Upvotes: 5