Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to have/lock unique index values of the Enum object in Javascript? [duplicate]

Reading the "recommended way" of dealing with ENUM Type in Javascript, I am still uncertain because I can compare the value with a forged value, while I should compare only to a "enum" type value:

 var DaysEnum = {"monday":1, "tuesday":2, "wednesday":3, ...}
 Object.freeze(DaysEnum)

 switch( day ){
   case "monday":
     return "Hello"
   case "tuesday":
     return "Hi"
   case "blahblahday":
     return "No"
 }

The strings I made the switch to compare against ("monday", "tuesday", "blahblahday") are totally free from my "enum type: DaysEnum", can be provided by the user and this could lead to some subtle errors not spotted by the interpreter (like typos).

Is there a way to have/lock unique index values of the Enum object?

like image 841
Simone Poggi Avatar asked Aug 17 '16 10:08

Simone Poggi


People also ask

Can enum have duplicate values?

CA1069: Enums should not have duplicate values.

Can we loop through enum JavaScript?

Can you loop through enum JavaScript? Iterating over the keys Of course, it's also possible to loop over the keys of a string enum, using Object.

What is the preferred syntax for defining enums in JavaScript?

The preferred syntax for defining enums in JavaScript is to use the objects see the code below:- var DaysEnum = Object. freeze({"monday":1, "tuesday":2, "wednesday":3, ...})

Can I convert enum to array?

To convert an enum to an array of objects: Use the Object. keys() method to get an array of the enum's keys. Filter out the unnecessary values for numeric enums.


1 Answers

A possible solution I found with ES2015 could be through Symbols

http://putaindecode.io/en/articles/js/es2015/symbols/

This way you have the unique "locked" values, like you have in other languages, like Java

 const DAY_MONDAY = Symbol();
 const DAY_TUESDAY = Symbol();

 switch(animal) {
   case DAY_MONDAY:
     return "Hello"
   case DAY_TUESDAY:
     return "Hi"
   //there is no way you can go wrong with DAY_BLAHBLAHDAY 
   //the compiler will notice it and throw an error
 }
like image 113
Simone Poggi Avatar answered Oct 20 '22 16:10

Simone Poggi