1

Pass value which is the combination of enum values and get the corresponding enum strings of it.

Here is my scenario,

enum EnumDays {
    NONE = 0,
    SUN = 1,
    MON = 2,
    TUE = 4,
    WED = 8,
    THU = 16,
    FRI = 32,
    SAT = 64,
    ALL = 127
}

I'll pass the value as 5, which is the combination of SUN & TUE (1 + 4 = 5).

I want to get "SUN" & "TUE" as result. How to achieve this?

1
  • You need to use bitwise operators. EnumDays.SUN|EnumDays.TUE Commented Oct 11, 2018 at 18:48

1 Answer 1

3

This can be done either by iterating through bits or by iterating through enum members. Iterating through bits seems a little cleaner. We take advantage of the fact that EnumDays maps values to keys (e.g., 1 to SUN) as well as keys to values (SUN to 1). (Nit: This approach won't find an enum value of 2147483648. 1 << 31, which is -2147483648, will work.)

function getDayNames(value: EnumDays) {
    let names = [];
    for (let bit = 1; bit != 0; bit <<= 1) { 
        if ((value & bit) != 0 && bit in EnumDays) { 
            names.push(EnumDays[bit]);
        }
    }
    return names;
}
Sign up to request clarification or add additional context in comments.

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.