Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript enum within an enum

I have the following "Enum" in javascript to indicate the state of my application:

var State = {
   STATE_A: 0,
   STATE_B: 1,
   STATE_C: 2
   //...
}

Now, I want each state to have a "sub-state". So for example, STATE_B could be in STATE_B1 or STATE_B2 ...

What would be the best way to structure this? Would I somehow nest an "enum" within the State "enum" ? Thanks

If there is a better way to structure this altogether (other than enums) I'm all ears. Basically I need to be able to set and check the state of my application, and each state can (but not necessary) have a sub-state attached to it which can be set and checked. Even better if the solution allows me to go more than 1 level of nesting deep.

like image 940
aeq Avatar asked Jul 29 '10 13:07

aeq


2 Answers

What you're doing isn't really enums. You're using native Javascript objects and just treating them like enums, which is perfectly acceptable when you want an enum-like object in Javascript.

To answer your question, yes, you can totally nest objects:

var State = {
   STATE_A: 0,
   STATE_B:{
      SUBSTATE_1 : "active",
      SUBSTATE_2 : "inactive"
   },
   STATE_C: 2
   //...
}

You then just use the dot notation in order to set those values, like

State.State_B.SUBSTATE_2 = "active".

like image 130
Nick Canzoneri Avatar answered Oct 07 '22 13:10

Nick Canzoneri


You could use some sort of bit-field if you want:

var State = function() {
  // Note this must increment in powers of 2.
  var subStates = 8;
  var A = 1 << subStates;
  var B = 2 << subStates;
  var C = 4 << subStates;
  var D = 8 << subStates;

  return {

    // A
    // Note this must increment in powers of 2.
    STATE_A:  A,
    STATE_A1: A | 1,
    STATE_A2: A | 2,
    STATE_A3: A | 4,
    STATE_A4: A | 8,
    STATE_A5: A | 16

    // B
    STATE_B:  B,
    STATE_B1: B | 1,

    // C
    STATE_C: C,
    STATE_C1: C | 1,
    STATE_C2: C | 2,
    STATE_C3: C | 4,
    STATE_C4: C | 8,

    // D
    STATE_D: D
  };
}();

// Set a state.
var x = State.STATE_A1; // Same as State.STATE_A | State.STATE_A1

// Determine if x has root state of A?
if(x & State.STATE_A == State.STATE_A) {
   console.log("Root state is A.");
}
else {
   console.log("Nope, not root state A.");
}

// Determine if x has sub-state A1?
if(x & State.STATE_A1 == State.STATE_A1) {
   console.log("A with Substate 1");
}

So the first 8 bits are reserved for setting the sub-state. You could, of course, increase this as long as the root-state and sub-state can fit inside a 32-bit integer. If you need explanation as to why/how this works (bit-wise operators), let me know.

like image 33
TheCloudlessSky Avatar answered Oct 07 '22 12:10

TheCloudlessSky