Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Understanding Javascript Function in base 16

Tags:

javascript

hex

I have this neat little function in JavaScript that is very useful and clean:

CreateGuid: function () {
        var guid = '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);
        });

        return guid;
    },

I would like to modify it slightly to be able to randomly generate an alpha numeric sequence.

The only part of this function that I don't under stand is:

r : (r & 0x3 | 0x8)

Apart from the fact that it is a ternary operator what does this do?

like image 348
Callum Linington Avatar asked Dec 25 '22 08:12

Callum Linington


2 Answers

It might be clearer if you look at the binary writing of 0x3 and 0x8 :

 0x3.toString(2) => 11
 0x8.toString(2) => 1000

What we're doing here is bitwise operations :

  • first a and with 11 at the bit level (truncating to only the two last bits, that is doing %4),

  • then a or with 1000 (setting one bit, adding 8).

The whole would probably be less confusing directly written as

var guid = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'
.replace(/x/g, function(){
   return  (Math.random()*16|0).toString(16)
})
.replace(/y/, function(){
   return  (Math.random()*4+8|0).toString(16)
})
like image 195
Denys Séguret Avatar answered Jan 14 '23 22:01

Denys Séguret


looks like it's equivalent to r % 4 + 8

http://jsfiddle.net/8TFMg/1/ :

0 & 0x3 | 0x8 = 8
1 & 0x3 | 0x8 = 9
2 & 0x3 | 0x8 = 10
3 & 0x3 | 0x8 = 11
4 & 0x3 | 0x8 = 8
5 & 0x3 | 0x8 = 9
6 & 0x3 | 0x8 = 10
7 & 0x3 | 0x8 = 11
8 & 0x3 | 0x8 = 8
9 & 0x3 | 0x8 = 9
10 & 0x3 | 0x8 = 10
11 & 0x3 | 0x8 = 11
12 & 0x3 | 0x8 = 8
13 & 0x3 | 0x8 = 9
14 & 0x3 | 0x8 = 10
15 & 0x3 | 0x8 = 11
like image 20
Peter Avatar answered Jan 14 '23 21:01

Peter