In JavaScript code, I have the following enum defined:
MyMessageIds = {
UndefinedId : 0,
FilenameId : 1,
BuildFileId : 2,
MovementArgsId : 3,
MoveId : 4,
ExecuteCommandId : 5
}
In a JavaScript function, I would like to be able to supply the string representation of an enum key (i.e. "MoveId") and return its integer value of 4. So how could I do this?
Just use bracket notation:
var MyMessageIds = {
UndefinedId : 0,
FilenameId : 1,
BuildFileId : 2,
MovementArgsId : 3,
MoveId : 4,
ExecuteCommandId : 5
};
function getValue(key) {
return MyMessageIds[key];
}
You could create some utility methods which take an object (enum) that figures out how to get the keys/values.
var MyMessageIds = {
UndefinedId : 0,
FilenameId : 1,
BuildFileId : 2,
MovementArgsId : 3,
MoveId : 4,
ExecuteCommandId : 5
}
function getEnumKeys(enumType) {
return Object.keys(MyMessageIds);
}
function getEnumValues(enumType) {
return getEnumKeys(enumType).map(function(key) {
return enumType[key];
});
}
function getEnumValue(enumType, key) {
return enumType[getEnumKeys(enumType).filter(function(k) {
return key === k;
}).pop() || ''];
}
document.body.innerHTML = '<pre>' + JSON.stringify({
'Enum Keys' : getEnumKeys(MyMessageIds),
'Enum Vals' : getEnumValues(MyMessageIds),
'Example' : {
'MoveId' : getEnumValue(MyMessageIds, 'MoveId')
}
}, null, 4) + '</pre>';
You could also create your own class object to represent an enum which has reusable methods.
function Enum() {
this.self = arguments[0];
}
Enum.prototype = {
keys : function() {
return Object.keys(this.self);
},
values : function() {
var me = this;
return this.keys(this.self).map(function(key) {
return me.self[key];
});
},
getValueByName : function(key) {
return this.self[this.keys(this.self).filter(function(k) {
return key === k;
}).pop() || ''];
},
getNameByValue : function(value) {
var me = this;
return this.keys(this.self).filter(function(k) {
return me.self[k] === value;
}).pop() || null;
}
};
var MyMessageIds = new Enum({
UndefinedId : 0,
FilenameId : 1,
BuildFileId : 2,
MovementArgsId : 3,
MoveId : 4,
ExecuteCommandId : 5
});
document.body.innerHTML = '<pre>' + JSON.stringify({
'Enum Keys' : MyMessageIds.keys(),
'Enum Vals' : MyMessageIds.values(),
'Example' : {
'MoveId' : MyMessageIds.getValueByName('MoveId'),
'Val(3)' : MyMessageIds.getNameByValue(3)
}
}, null, 4) + '</pre>';
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With