Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
230 views
in Technique[技术] by (71.8m points)

Explanation of syntax on GUID / UUID Function in JavaScript

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());
question from:https://stackoverflow.com/questions/65861596/explanation-of-syntax-on-guid-uuid-function-in-javascript

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
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)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...