Created
June 15, 2022 14:34
-
-
Save ranaroussi/aed8327820f2a8ee65c86349cba90bac to your computer and use it in GitHub Desktop.
Javascript enum using Object.freeze
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
class Enum { | |
constructor(...args) { | |
if (args.length === 0) { | |
throw new Error('Enum must be initialized with at least one argument'); | |
} | |
let obj = (args.length === 1) ? args[0] : args; | |
if (args.length > 1 || Array.isArray(obj)) { | |
obj = Object.assign({}, ...obj.map((x) => ({ [x]: x }))); | |
} | |
[...Object.entries(obj)].forEach((items) => { | |
this[items[0]] = items[1]; | |
}); | |
Object.freeze(this); | |
} | |
} | |
module.exports = Enum; |
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
const Enum = require('./enum'); | |
console.log('as args →', new Enum('a', 'b', 'c')); | |
console.log('as array →', new Enum(['a', 'b', 'c'])); | |
console.log('as dict →', new Enum({ 'a': 'b', 'c': 'd' })); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment