Enums should be objects with methods
Opened this issue · 1 comments
matthewadams commented
Java's implementation of enums is quite good. The issue rwaldron/proposal-enum-definitions#5 describes it quite well for JavaScript. Let's please not forget to consider this. I, for one, would love to have JavaScript enums modeled after Java.
rauschma commented
I agree:
- I almost never use enums as lookup tables, but as collections of named values.
- Being able to define custom methods and properties is often helpful.
- I also like having unique values by default.
If you do want a lookup table, you can still get it via Java’s enum pattern:
class Mode {
static user_r = new Mode(0b100000000);
static user_w = new Mode(0b010000000);
static user_x = new Mode(0b001000000);
static group_r = new Mode(0b000100000);
static group_w = new Mode(0b000010000);
static group_x = new Mode(0b000001000);
static all_r = new Mode(0b000000100);
static all_w = new Mode(0b000000010);
static all_x = new Mode(0b000000001);
constructor(n) {
this.n = n;
}
}
assert.equal(
Mode.user_r.n | Mode.user_w.n | Mode.user_x.n |
Mode.group_r.n | Mode.group_x.n |
Mode.all_r.n | Mode.all_x.n,
0o755);
assert.equal(
Mode.user_r.n | Mode.user_w.n | Mode.user_x.n |
Mode.group_r.n,
0o740);
As an enum, the class could look like this:
enum Mode {
user_r(0b100000000);
user_w(0b010000000);
user_x(0b001000000);
group_r(0b000100000);
group_w(0b000010000);
group_x(0b000001000);
all_r(0b000000100);
all_w(0b000000010);
all_x(0b000000001);
constructor(n) {
this.n = n;
}
}
The enum would also have many of the properties suggested by the proposal: Mode.keys
, Mode.entries()
, etc.
More examples and thoughts: https://2ality.com/2020/01/enum-pattern.html
Alternatively, I also like the “algebraic data type” style: #6
I’d prefer not to mix it with “lookup table” style, though.