Reputation: 6522
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();
},
}
Upvotes: 4
Views: 1020
Reputation: 665276
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);
Upvotes: 6
Reputation: 816970
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 = {};
Upvotes: 3