Implementation example of generating GUID using JavaScript

Source: Internet
Author: User
Tags current time repetition

GUID (globally unified identifier) refers to the number generated on a machine, which ensures that all machines in the same time and space are unique. Generally, the platform provides APIs for generating GUIDs. The generation algorithm is very interesting. It uses Ethernet card addresses, nanoseconds, chip ID codes, and many possible numbers. The unique defect of GUID is that the generated result string is large.
 
GUID format
Xxxxxxxx-xxxx-xxxxxxxxxxxx
We all know that GUID is of little use in front-end development, but if you need to insert an ID, and this ID corresponds to the background and other operations that require GUID, for convenience, we can still generate a GUID.
 
Generally, it is easy to generate a GUID in the background or database languages such as SQL, Java, and C #. The front-end does not directly generate a GUID, and you can only write it by yourself. However, because the GUID needs to obtain the address of the Ethernet card and the number of the time in the nanosecond level. It is difficult for the front-end to obtain this information (please tell me if you know it), and we can simulate and generate a GUID. The code is as follows:
 
JavaScript generates GUID
/*
* Function: generate a GUID code. The GUID consists of 14 or less date and 18 or more hexadecimal random numbers. The GUID has a certain repetition probability, but the repetition probability is extremely low, in theory, the probability of repetition is 1/(16 ^ 18) for every 10 ms, that is, 1 in the 18 power of 16. The probability of repetition is as low as negligible.
* Disclaimer: This code is designed for the author to learn. For example, it has nothing to do with the author if the user suffers losses due to code problems during use.
*/

 
Function GUID (){
This. date = new Date ();

/* Determine whether the initialization is successful. If the following code is initialized, the following code will not be executed, but will be executed only once */
If (typeof this. newGUID! = 'Function '){
       
/* Generate the GUID code */
GUID. prototype. newGUID = function (){
This. date = new Date ();
Var guidStr = '';
SexadecimalDate = this. hexadecimal (this. getGUIDDate (), 16 );
SexadecimalTime = this. hexadecimal (this. getGUIDTime (), 16 );
For (var I = 0; I <9; I ++ ){
GuidStr + = Math. floor (Math. random () * 16). toString (16 );
            }
GuidStr + = sexadecimalDate;
GuidStr + = sexadecimalTime;
While (guidStr. length <32 ){
GuidStr + = Math. floor (Math. random () * 16). toString (16 );
            }
Return this. formatGUID (guidStr );
        }

/*
* Function: Get the GUID format of the current date, that is, the 8-digit date: 19700101
* Return value: return the string of The GUID date format.
*/
GUID. prototype. getGUIDDate = function (){
Return this. date. getFullYear () + this. addZero (this. date. getMonth () + 1) + this. addZero (this. date. getDay ());
        }

/*
* Function: Get the GUID format of the current time, that is, the 8-digit time, including milliseconds, 2-digit in milliseconds: 12300933
* Return value: return the string of The GUID date format.
*/
GUID. prototype. getGUIDTime = function (){
Return this. addZero (this. date. getHours () + this. addZero (this. date. getMinutes () + this. addZero (this. date. getSeconds () + this. addZero (parseInt (this. date. getMilliseconds ()/10 ));
        }

/*
* Function: add 0 to the front of a single-digit positive integer. If it is a string that can be converted into a non-NaN number, it can also be implemented.
* Parameter: indicates a string that is ready to add a number 0 or can be converted to a number.
* Return value: if the condition is met, the string type after 0 is added is returned. Otherwise, the string of the user is returned.
*/
GUID. prototype. addZero = function (num ){
If (Number (num). toString ()! = 'Nan '& num> = 0 & num <10 ){
Return '0' + Math. floor (num );
} Else {
Return num. toString ();
            }
        }

/*
* Function: convert the value in y to the value in x.
* Parameter: the second parameter indicates the value to be converted. The second parameter indicates the hexadecimal value to be converted. The second parameter is optional, indicating the current hexadecimal number. If this parameter is left blank, the value is 10.
* Return value: returns the converted string.
*/
GUID. prototype. hexadecimal = function (num, x, y ){
If (y! = Undefined ){
Return parseInt (num. toString (), y). toString (x );
} Else {
Return parseInt (num. toString (). toString (x );
            }
        }

/*
* Function: format a 32-bit string in GUID mode.
* Parameter: the first parameter represents a 32-bit string.
* Return value: a string in the standard GUID format.
*/
GUID. prototype. formatGUID = function (guidStr ){
Var str1 = guidStr. slice (0, 8) + '-',
Str2 = guidStr. slice (8, 12) + '-',
Str3 = guidStr. slice (12, 16) + '-',
Str4 = guidStr. slice (16, 20) + '-',
Str5 = guidStr. slice (20 );
Return str1 + str2 + str3 + str4 + str5;
        }
    }
}
Usage
 
You only need to save it in a JS file and reference it.
 
Then we only need
Var guid = new GUID ();
Alert (guid. newGUID ());
The GUID code can be obtained. The implementation principle is very simple. Here, the system time and more than 18 hexadecimal random numbers are used, and the system time is converted to hexadecimal, in this way, although there is still a possibility of repetition, the probability of repetition is extremely low and negligible.
 
The above is my method for generating GUID. If you have any better method, please let me know. Thank you!

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.