Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Enum flags in JavaScript

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?

like image 660
Andrey Avatar asked Oct 26 '09 17:10

Andrey


People also ask

What are enum flags?

Enum Flags Attribute The idea of Enum Flags is to take an enumeration variable and allow it hold multiple values. It should be used whenever the enum represents a collection of flags, rather than representing a single value. Such enumeration collections are usually manipulated using bitwise operators.

What is enum in JavaScript?

Enums or Enumerated types are special data types that set variables as a set of predefined constants. In other languages enumerated data types are provided to use in this application. Javascript does not have enum types directly in it, but we can implement similar types like enums through javascript.


1 Answers

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:

  • Understanding bitwise operations in javascript
  • How to check my byte flag?
like image 174
Christian C. Salvadó Avatar answered Oct 14 '22 13:10

Christian C. Salvadó