Created
August 15, 2020 16:19
-
-
Save gm50x/080946dd64192ddd18fa9ecb7c0cb87d to your computer and use it in GitHub Desktop.
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
// 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