'Is there a concise way to write a set of enums as strings?
When i write enums in javascript I often write:
const movementState = {
stopped: 'stopped',
walking: 'walking',
running: 'running',
};
This enables me to use it like movementState.stopped and linting ensures it exists, also if I log it, it's value is human readable.
I'd like something like:
enum movementState = {stopped, walking, running};
Note: I have no interest in doing this in typescript. I do my survival work-job in TS, I do my passion in JS.
I'm not super up to date w the standard... so I was hoping maybe something new was added in one of the stages or something. Thanks~
Solution 1:[1]
One option would be to map an array of the strings to an array of entries, using the string as the value and as the key, then turn it into an object with Object.fromEntries. Not extraordinarily concise, but I'm not sure if you can get anything better.
const makeEnum = strs => Object.fromEntries(
strs.map(str => [str, str])
);
const movementState = makeEnum(['stopped', 'walking', 'running']);
console.log(movementState.running);
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
