Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

implement enum as immutable class in modern javascript (es2015)

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

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

However, it's a bit annoying to write all this getters. So I'm curious - is there a chance to optimize this with compute method names and maybe some other es2015 features.

In result I dream to have something like that:

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();
      },
    }
like image 864
silent_coder Avatar asked Jan 08 '23 02:01

silent_coder


1 Answers

A class makes just no sense. You don't a want a function with static getters. You just want an immutable object - and that's easy:

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

Of course you can also dynamically create that if listing all properties is too cumbersome:

const AlphabetEnum = {};
for (let i=0; i<26; i++)
    AlphabetEnum[String.fromCharCode(65+i)] = String.fromCharCode(97+i);
Object.freeze(AlphabetEnum);
like image 133
Bergi Avatar answered Jan 09 '23 20:01

Bergi