4

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();
      },
    }

2 Answers 2

6

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);
Sign up to request clarification or add additional context in comments.

Comments

3

You'd do it the same way is in ES5, with 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
  });
});

However, using a class just for static properties is an anti-pattern IMO. In that case you can as well use a plain object:

var AlphabetEnum = {};

8 Comments

You may want to remove the comma after configurable: true, otherwise nice answer :).
@Arg0n: Why should I do that?
Because that's prettier! (Which is totally a fact, not an opinion) v++
@FelixKling Hmm, i just think it looks like an object and that you will get syntax error with the comma after the last property? But since you say you don't need to i guess you're right.
@Arg0n: A trailing comma in an object literal is not a syntax error :)
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.