0

In the startup code for the MEAN framework there's a line of code shown below

if (!!~this.roles.indexOf('*')) {

It's located in the public/modules/core/services/menus.client.service.js file in the shouldRender function.

var shouldRender = function(user) {
        if (user) {
            if (!!~this.roles.indexOf('*')) {  //Here is the code
                return true;
            } else {
                for (var userRoleIndex in user.roles) {
                    for (var roleIndex in this.roles) {
                        if (this.roles[roleIndex] === user.roles[userRoleIndex]) {
                            return true;
                        }
                    }
                }
            }
        } else {
            return this.isPublic;
        }

        return false;
};
Juan
  • 3,433
  • 29
  • 32
abcf
  • 685
  • 2
  • 10
  • 25
  • They should have used `this.roles.indexOf('*')>-1`, which has the same number of characters but is clearer. Or `~this.roles.indexOf('*')`, which is shorter. – Oriol Dec 31 '14 at 02:02
  • Yes, there's no need at all to convert the value to boolean since any value is truth-evaluable – Luis Masuelli Dec 31 '14 at 02:03

1 Answers1

0

It evaluates whether the '*' is found or not, by converting it to boolean. It is plain Javascript.

~[1, 2, 3, 4].indexOf(4)
//returns -4 (bit inversion of 3)

indexOf returns 0, 1, 2, 3... when the element exists. Bit inversion converts those values to -1, -2, -3, -4, ... respectively.

When the element does not exist, -1 is returned. By bit inversion, 0 remains.

So, when the element exists, you get a nonzero. When the element does not exist, you get 0.

By prepending !!, you are converting the value to boolean (0 is a falsey value, !0 is true, !!0 is false; x (if not zero) is a nonfalsey value, !x is false, !!x is true).

So it could be understood as: if '*' is in this.roles ...

Luis Masuelli
  • 12,079
  • 10
  • 49
  • 87