Reputation:
I wanted to create enum in javascript and I did the following code and I want to verify that this is the right way.
var dataStates = {
withMock: "withM",
withoutMock: "withoutM",
};
is it ok?
I want for example to use it like
oCation.dataMode === dataStates.withMock
and that state.data.withMock will hold the value but Im not sure if it's the right way...
Upvotes: 0
Views: 228
Reputation: 48277
Javascript does not have a proper (static) enum
type, but you can achieve something very close using the same code Typescript generates for its enums.
To offer enums but still be valid JS, you want an object where each enum element (name) is a key, mapping to a unique value (typically an int, since most languages with enums back them with integer values).
For an enum like enum Color {Red, Green, Blue};
, you would end up with code containing:
Color[Color["Red"] = 0] = "Red";
Color[Color["Green"] = 1] = "Green";
Color[Color["Blue"] = 2] = "Blue";
This creates an object with a key for each enum element's name, and for each element's value. The final object looks like:
var Color;
(function(Color) {
Color[Color["Red"] = 0] = "Red";
Color[Color["Green"] = 1] = "Green";
Color[Color["Blue"] = 2] = "Blue";
})(Color || (Color = {}));
document.getElementById("result").textContent = JSON.stringify(Color);
<pre id="result"></pre>
This allows you to access the enum values using the traditional Color.Red
syntax, but also allows you to map values back into names using Color[Color.Red]
(or a variable containing one of the enum values).
For example:
var Color;
(function(Color) {
Color[Color["Red"] = 0] = "Red";
Color[Color["Green"] = 1] = "Green";
Color[Color["Blue"] = 2] = "Blue";
})(Color || (Color = {}));
document.getElementById("red").textContent = Color.Red; // Should print "0"
var currentColor = Color.Green;
document.getElementById("green").textContent = Color[currentColor]; // Should print "Green"
currentColor = Color.Blue;
document.getElementById("blue").textContent = Color[currentColor]; // Should now print "Blue"
<pre id="red"></pre>
<pre id="green"></pre>
<pre id="blue"></pre>
Upvotes: 1
Reputation: 13570
What you have created is an object with named properties. This is not an Enum in the Java sense. Which is to say there are no language constraints enforcing uniqueness and single instances. However what you have done will meet the requirements you specified in your question.
Upvotes: 1