enumjs icon indicating copy to clipboard operation
enumjs copied to clipboard

Rust-like Enums

Open wldcordeiro opened this issue 9 years ago • 2 comments

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

wldcordeiro avatar Feb 26 '16 22:02 wldcordeiro

Sorry I just saw this! Somehow I didn't get a notification. I will take a look at this tomorrow morning.

vivin avatar Mar 02 '16 08:03 vivin

@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?

vivin avatar Mar 04 '16 17:03 vivin