Created
August 31, 2017 12:11
-
-
Save blogscot/6b1e7cf1c5e5b9e3db9afdb1853af6ff to your computer and use it in GitHub Desktop.
A basic JavaScript Enum constructor function
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// A basic Enum constructor function | |
const Enum = (...values) => { | |
let newEnum = {} | |
for (const value of values) { | |
Object.assign(newEnum, { | |
[value]: value | |
}) | |
} | |
return newEnum | |
} | |
// Declare a new Enum | |
let powerState = Enum("Initial", "On", "Off") | |
console.log(powerState) // { Initial: 'Initial', On: 'On', Off: 'Off' } | |
// Some examples | |
let state1 = powerState.Initial | |
let state2 = powerState.On | |
let currentState = powerState.Initial | |
state1 === state2 // false | |
currentState == state1 // true |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment