I\'m rebuilding an old Java project in Javascript, and realized that there\'s no good way to do enums in JS.
The best I can come up with is:
const C
Here is my approach, including some helper methods
export default class Enum {
constructor(name){
this.name = name;
}
static get values(){
return Object.values(this);
}
static forName(name){
for(var enumValue of this.values){
if(enumValue.name === name){
return enumValue;
}
}
throw new Error('Unknown value "' + name + '"');
}
toString(){
return this.name;
}
}
-
import Enum from './enum.js';
export default class ColumnType extends Enum {
constructor(name, clazz){
super(name);
this.associatedClass = clazz;
}
}
ColumnType.Integer = new ColumnType('Integer', Number);
ColumnType.Double = new ColumnType('Double', Number);
ColumnType.String = new ColumnType('String', String);