Skip to content

Instantly share code, notes, and snippets.

@gm50x
Created August 15, 2020 16:19
Show Gist options
  • Save gm50x/080946dd64192ddd18fa9ecb7c0cb87d to your computer and use it in GitHub Desktop.
Save gm50x/080946dd64192ddd18fa9ecb7c0cb87d to your computer and use it in GitHub Desktop.
// Function to create the enums
const getEnum = (obj) => {
const EEnum = {}
if (Array.isArray(obj)) {
obj.forEach((enumerator, i) => EEnum[enumerator] = i)
} else {
Object.getOwnPropertyNames(obj)
.forEach(property => {
EEnum[property] = obj[property]
})
}
// Prevent file modification after creation of the enum
Object.freeze(EEnum)
return EEnum
}
// Get enums
const EStatus = getEnum(['Inactive', 'Active'])
const EDataType = getEnum({ Foo: 1000, Bar: 2000, Fizz: 3000, Buzz: 4000 })
// See values
console.log(EStatus)
console.log(EDataType)
// Try to alter the enum props
EStatus.Foo = 200
EDataType.Bin = 5000
// They are not altered because the object has been frozen
console.log(EStatus)
console.log(EDataType)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment