If you want to convert values in the enum
namespace, consider adding a static function for that purpose.
For extracting set bits from a number efficiently, you can use this trick: n & (~n+1)
will give 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));
The output is:
[ 'Administrator' ]
[ 'SU', 'Administrator' ]
To convert numbers, simply push the bit
without needing a lookup table.