1

I am currently working with angularjs and there is this pieceof code. I dont get What does it return?

    authorize: function(accessLevel, role) {
        if(role === undefined) {
            role = Session.role;
        }
        return accessLevel.bitMask & role.bitMask;
    },

Some tests

        console.log(1&2);     //0
        console.log(3&7);     //3
        console.log(5&11);    //1
        console.log(0.5&11);  //0

Anyone has any idea?

Edit: I am sorry that this question was already asked. But since i didnt know the keyword bitwise, or couldnt find any match with the previous topic keywords in my presearch i appriciate the answers here!

Oguzhan
  • 724
  • 6
  • 12
  • 4
    https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Operators/Bitwise_Operators – Marc B Aug 13 '14 at 20:01

2 Answers2

2

To put it very simply, & is a bit-wise AND operation. The return expression is checking whether the bits in role "jive" with the bits in accessLevel (i.e. is this role authorized?).

To add some detail, let's look at this line:

console.log(3&7);     //3

In bit-land, we have:

3: 00000011
7: 00000111
===========
&: 00000011 = 3

The result of the bit-wise AND operation on the two bytes is arrived at by AND-ing each bit column based on these rules:

0 & 0 => 0
0 & 1 => 0
1 & 0 => 0
1 & 1 => 1

If you think of each 0 as false and each 1 as true, then it makes a lot of sense. See the Wikipedia article on Truth tables for more on this.

Cᴏʀʏ
  • 105,112
  • 20
  • 162
  • 194
0

Returns a one in each bit position for which the corresponding bits of both operands are ones.

https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Operators/Bitwise_Operators

Raab
  • 34,778
  • 4
  • 50
  • 65