Given:
Enum: {1, 4, 16}
Flags: 20
When: I provide the Flags value to a function
Then:
The output will be an array of flags corresponding to the given Enum: [4, 16]
Note: I attempted to manually convert the Enum to an array and treat values as numbers. However, I encountered difficulties when transitioning to TS and I aim to create a function that is adaptable in case the Enum is modified. I prefer not to hardcode it. Any assistance would be greatly appreciated!
enum Enum {
one = 1,
four = 4,
sixteen = 16,
}
const Flags: number = 20;
function getEnumValues(flags: number): Enum[] {
const enumFlags = [1, 4, 16];
const enums: Enum[] = [];
enumFlags.forEach(ef => {
if ((ef & flags) != 0) {
enums.push(ef);
}
})
return enums;
}
console.log(getEnumValues(Flags));
Solution referred from: Typescript flagged enum get values. However, this solution does not align with my Enum as it lacks sequences 2 and 8.