How to use Enum with hierarchy / nesting and subgroup

Asked

Viewed 240 times

-4

I have a enum class called Example as follows:

export enum Example {
// enums pertercentes ao grupo A:
   enumA1,
   enumA2,
   enumA3,
// enums pertercentes ao grupo B:
   enumB1,
   enumB2,
   enumB3,
// enums pertercentes ao grupo C:
   enumC1,
   enumC2,
   enumC3;
}

It is important to my project that all enums with which work belong to Example (since this is an argument in a class constructor).

How do I use the hierarchy / nesting of Enum to achieve the following:

A method that tests whether an Enum is in the group A, B or C. For example, something like Example.enumA1.isGroupBelonging (Group.A) or isGroupBelonging (Example.enumA1, Group.A) would be a public method that returns true .

Being able to do the same thing with subgroups of the group A, B and C. For example, the group A may have subgroups a, b and c. Then I want a method that does something like Example.enumA1.isSubGroupBelonging (SubGroup.a), which is a booleano public.

A way to do all this without having any name of enum which obstructs my code. For example, it would be good to only refer to Example.enumA1 in my other classes without having to reference him using something like Example.enumA1 (Group.A, SubGroup.a) or Example.enumA1.Group.A.SubGroup.a

  • 2

    It is not better to use a Pattern?

  • Qual Pattern @Virgilionovic ?

  • Basically I could not say because I do not know the real problem, what is in your question is too vague, there is no example code that we always ask here, a code that represents your doubt, usually a interface of contract and classes implementing this interface, something structural or even something that can be simpler.

  • So it doesn’t make any sense your comment on the use of Pattern @Virgilionovic

  • If I understood, it wouldn’t be simpler to have several separate enums for each group and have a type that could be any of these groups (type abc = enumA1 | enumA2 | enumB1 ...) or even a specific group (type a = enumA1 | enumA2 | enumA3)? So you keep the enums separate and use the types to group these enums in the way that suits you

1 answer

4


I don’t know if this might help you, but there is this alternative through Object

    const groupA = Object.freeze({
        A1: "A1",
        A2: "A1",
    })
    
    const groupB = Object.freeze({
        B1: "A1",
        B2: "A1",
    })
    
    const groupC = Object.freeze({
        ...groupA,
        ...groupB
    })
    
    Object.keys(groupC).includes(groupA.A1)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.