views:

350

answers:

3

I need to emulate enum type in Javascript and approach seems pretty straight forward:

var MyEnum = {Left = 1; Right = 2; Top = 4; Bottom = 8}

Now, in C# I could combine those values like this:

MyEnum left_right = MyEnum.Left | MyEnum.Right

and then I can test if enum has certain value:

if (left_right && MyEnum.Left == MyEnum.Left) {...}

Can I do something like that in Javascript?

+4  A: 

In javascript you should be able to combine them as:

var left_right = MyEnum.Left | MyEnum.Right;

Then testing would be exactly as it is in your example of

if ( (left_right & MyEnum.Left) == MyEnum.Left) {...}
Mike Clark
Rytmis
Whoops, thanks for the catch. Edited
Mike Clark
+1  A: 

Yes, bitwise arithmetic works in Javascript. You have to be careful with it because Javascript only has the Number data type, which is implemented as a floating-point type. But, values are converted to signed 32-bit values for bitwise operations. So as long as you don't try to use more than 31 bits, you'll be fine.

Warren Young
+5  A: 

You just have to use the bitwise operators:

var myEnum = {
  left: 1,
  right: 2,
  top: 4,
  bottom: 8
}

var myConfig = myEnum.left | myEnum.right;

if (myConfig & myEnum.right) {
  // right flag is set
}

More info:

CMS
I wish I could mark both Mike Clark's and your answers, but I can only do one and Mike has much less points, so I think you won't be upset if I mark his answer :)
Andrey
@Andrey: Don't worry!, Mike's answer is also completely valid :-)
CMS