HARSH BAJPAI
HARSH BAJPAI

Reputation: 45

Detailed explanation for this function needed

I was going through a function whose main purpose is to generate a unique id for every user of the application can someone explain me the working of the function.

guid: function() {
    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);
    });
  },

I need explanation on replace(/[xy]/g){i.e what does this means}, than what does (r&0x3|0x8) means.

Upvotes: 0

Views: 1720

Answers (2)

bvdb
bvdb

Reputation: 24770

By 2013 this function started popping up on stackoverflow (e.g. here). If you search for the keyword 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx' you can easily find 20 mentions of it, right here on stackoverflow.

And trying to trace it back further, the earliest mention I could find was on github in 2011, when somebody experimented to find a shorter function. (i.e. here). In fact, the last solution which he offered seems to be shorter and probably faster too. Nevertheless, the version you referenced is the most popular one.

To avoid further copying, you may want to replace it by an external library.

npm install uuid

And replace that code with

import { v4 as uuidv4 } from 'uuid';
uuidv4(); 

As explained here.

Upvotes: 1

Eric
Eric

Reputation: 2705

/[xy]/g is a RegEx literal. String.prototype.replace(..) takes RegEx or a substring as its first argument, and new substring or a function as its second.

/[xy]/g is a regular expression that matches a single character x or y in the original string.

replace(..) will replace all substrings that match the regex ('x' or 'y') to another string using the given function.

The function basically gives a random character for replace(..) to replace 'x' or 'y' with, and it does additional & operation for 'y' (which still gives a random character, but a different one).

If it's 'y', it is assigned (r&0x3|0x8).

In (r&0x3|0x8), r is the random number generated earlier. 0x3 is 11 in binary(base 2). r&0x3 extracts the lowest two bits of r. For example, if r, the random number, was 6. 6 in base 2 is 110. (110)&(11) extracts the lowest bit, so the result is (10) in base 2, which translate to 2 in base 10. So 2 is assigned. If the value of r&0x3 is 0, the |0x8 part makes it fall back to 0x8, which is 8. To learn more about this, please read up on bitwise operators

In summary, the 'x' and 'y' in the original string xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx is a placeholder, and it generates some kind of random id such as b9e08d48-0dfc-4a27-ba77-4a94b363b311, by replacing them with random characters.

Upvotes: 6

Related Questions