Implement enum as an immutable class in modern javascript (es2015)

I need help. I want to implement Enum with modern javascript. I want it to be immutable and think that it will look something like this:

class AlphabetEnum{
  static get A(){
     return 'a';
  },
  static get B(){
     return 'b';
  }
 ...
}

However, it is a little annoying to write all these getters. Therefore, I am wondering if it is possible to optimize this using the names of the calculation methods and, possibly, some other es2015 functions.

As a result, I dream of having something like this:

let alph = [a, b, c, ..., z];
class AlphabetEnum{
      static get [some__clever_way_to_resolve_names_from_<alph>](){
         return some_clever_way_to_understand_what's_called();
      },
    }
+4
source share
2 answers

A class just doesn't make sense. You do not need a function with static getters. You just need an immutable object - and this is easy:

const AlphabetEnum = Object.freeze({
    A: "a",
    B: "b",
});

, , :

const AlphabetEnum = {};
for (let i=0; i<26; i++)
    AlphabetEnum[String.fromCharCode(65+i)] = String.fromCharCode(97+i);
Object.freeze(AlphabetEnum);
+6

, ES5, Object.defineProperty:

class AlphabetEnum {}

['a', 'b', 'c', ..., 'z'].forEach(letter => {
  Object.defineProperty(AlphabetEnum, letter.toUpperCase(), {
    get: () => letter,
    configurable: true, // remove this line if not needed / wanted
  });
});

class - - . :

var AlphabetEnum = {};
+3

Source: https://habr.com/ru/post/1617992/


All Articles