Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

convert javascript enum key string to value

Tags:

javascript

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?

like image 740
chuckp Avatar asked Sep 17 '16 20:09

chuckp


2 Answers

Just use bracket notation:

var MyMessageIds = {
    UndefinedId : 0,
    FilenameId : 1,
    BuildFileId : 2,
    MovementArgsId : 3,
    MoveId : 4,
    ExecuteCommandId : 5
};

function getValue(key) {
    return MyMessageIds[key];
}
like image 98
baao Avatar answered Oct 12 '22 19:10

baao


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>';
like image 42
Mr. Polywhirl Avatar answered Oct 12 '22 18:10

Mr. Polywhirl