简体   繁体   中英

Typescript flagged enum get values

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]

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]);
    }
}

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM