Skip to content

Instantly share code, notes, and snippets.

@ranaroussi
Created June 15, 2022 14:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ranaroussi/aed8327820f2a8ee65c86349cba90bac to your computer and use it in GitHub Desktop.
Save ranaroussi/aed8327820f2a8ee65c86349cba90bac to your computer and use it in GitHub Desktop.
Javascript enum using Object.freeze
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;
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