Hacker News new | ask | show | jobs
by pmontra 4018 days ago
It was an example of replacing constants with symbols when the value of the constant really doesn't matter. Purposely not fancy stuff. I understand the advantages of enums (among the others, their values are constrained) but does JS have enums?
1 comments

> does JS have enums?

No, but TypeScript and Dart do.

Enums don't really work without types.

But using Symbols for fake enums is probably a good idea.

    class Enum {
      constructor(...props) {
        props.forEach(p => this[p] = Symbol(p));
      }
    }
    const dir = Object.freeze(new Enum(...'NESW'));
    console.log(dir.E === dir.E); // true
    console.log(dir.E === dir.N); // false
Slightly awkward, but this might be about as good as it gets.
I should have used Object.freeze(this) in the c'tor.