2

I have flagged enum below

enum PermissionEnum {
    SU = 1 << 0,            // 1
    Administrator = 1 << 1, // 2
    User = 1 << 2           // 4
}

For given value 6, how can I get

string[] -> ['Administrator', 'User']

number[] -> [2,4]

2 Answers 2

3

You can add a static function into the enum namespace and use that to do the conversion.

Also you can use a trick to extract the set bits from a number without having to iterate over all the unset ones: n & (~n+1) gives you the lowest set bit.

enum PermissionEnum  {
    SU = 1 << 0,            // 1
    Administrator = 1 << 1, // 2
    User = 1 << 2           // 4
}
namespace PermissionEnum {
  export function toValues(n: PermissionEnum) {
    const values: string[] = [];
    while (n) {
      const bit = n & (~n+1);
      values.push(PermissionEnum[bit]);
      n ^= bit;
    }
    return values;
  }
}
console.log(PermissionEnum.toValues(PermissionEnum.Administrator));
console.log(PermissionEnum.toValues(PermissionEnum.Administrator + PermissionEnum.SU));

Output is:

[ 'Administrator' ]
[ 'SU', 'Administrator' ]

The conversion to numbers would be the same but just pushing bit without a lookup.

Sign up to request clarification or add additional context in comments.

Comments

2

That should work:

let x: PermissionEnum = PermissionEnum.Administrator | PermissionEnum.User;

const permNum: number[] = [];
const permStr: string[] = [];
let i = 0;
let perm: number;
while (PermissionEnum[perm = 1 << i++]) {
    if (x & perm) {
        permNum.push(perm);
        permStr.push(PermissionEnum[perm]);
    }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.