Skip to content

Instantly share code, notes, and snippets.

@blogscot
Created August 31, 2017 12:11
Show Gist options
  • Save blogscot/6b1e7cf1c5e5b9e3db9afdb1853af6ff to your computer and use it in GitHub Desktop.
Save blogscot/6b1e7cf1c5e5b9e3db9afdb1853af6ff to your computer and use it in GitHub Desktop.
A basic JavaScript Enum constructor function
// 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