简体   繁体   中英

Get all values represent decimal value in flag enum

I am using typescript to declare enum of type flag as following

export enum OperatorEnum{    
    None = 0x0,
    Equal = 0x1,
    NotEqual = 0x2,
    GreaterThan = 0x4,
    LessThan = 0x10,
    GreaterOrEqual = 0x20,
    LessOrEqual = 0x40,
    Contains = 0x80,
    In = 0x100,
}

And I received a decimal value such as 119. The values represent 119 are {Equal, NotEqual, GreaterThan, LessThan, GreaterOrEqual, LessOrEqual}

How I can extract all values using |form the enum.

Enums in TypeScript are objects, and both the enum's keys and values are property values. In your case, you can differentiate the keys from the values because your values are numbers.

So we look for values that are numbers and for which a bitwise AND with 199 ( enumValue & 119 ) is not 0:

enum OperatorEnum {
    None = 0x0,
    Equal = 0x1,
    NotEqual = 0x2,
    GreaterThan = 0x4,
    LessThan = 0x10,
    GreaterOrEqual = 0x20,
    LessOrEqual = 0x40,
    Contains = 0x80,
    In = 0x100,
}
const value = 0x77; // 119 in decimal
const matches = Object.values(OperatorEnum)
    .filter(v => typeof v === "number" && (value & v) !== 0)
    .map(v => OperatorEnum[v as number]); // type guaranteed by `filter`
console.log(matches);

Playground link

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