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();
},
}
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With