Rust-like Enums
Not sure if the name makes the most sense, but i'd like to be able to associate data with enum variants and work with them like you can here
Example usage:
const Message = Enum.define('Message', {
constants: {
Move: { x: 0, y: 0 },
},
});
let x = Message.Move(3, 4);
Additional reading: https://doc.rust-lang.org/book/enums.html
Sorry I just saw this! Somehow I didn't get a notification. I will take a look at this tomorrow morning.
@wldcordeiro This is interesting. Unfortunately, I don't think it will be as easy to enforce the same level of type-safety you get with Rust because of JavaScript's dynamic typing.
For example, you could associate x and y with Move, and then r, g, b with another constant called ChangeColor, but let's say you have a function that accepts an instance of the Message enum. While you could say that the argument is an instance of Message, it would be difficult to figure out what particular constant of the enum it is. Normally that doesn't matter since each constant in the enum will look like every other constant (i.e., have the same set of properties), but in this case you would have to iterate over every constant of the enum to figure out which one it is, so that you can figure out what properties it has. I think this ends up making the enum less type-safe.
One way around this might be to allow an enum to be subclassed. It's more verbose to do it this way (since you would have to define a new enum type for each variant), but you would still get the type-safety.
What do you think?