Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cast int to enum in javascript

Tags:

javascript

How do you efficiently cast an int to enum in javascript?

Say I have this enum

enuTable = // Table enum
{
    enuUnknown: 0,
    enuPerson: 1,
    enuItem: 2,
    enuSalary: 3,
    enuTax: 4,
    enuZip: 5,
    enuAddress: 6,
    enuLocation: 7,
    enuTasks: 8,

};

In part of the code I get a return value from an AJAX call that is a number corresponding to one of the above tables.

I can write a switch transforming the value, however is there a more efficient (briefer) way of casting an int to enum? One reason is, I don't want to constantly have to change the switch, in case I change the enum. I guess I could use an array with the enum names and construct an identifier to index into the enum, however again, I would need to change the array every time the enum is changed. I guess what I am looking for is a transparent method, that doesn't require beforehand knowledge of the enum.

like image 554
aggaton Avatar asked Jul 22 '14 18:07

aggaton


2 Answers

Like this

var keys = Object.keys(enuTable).sort(function(a, b){
    return enuTable[a] - enuTable[b];
}); //sorting is required since the order of keys is not guaranteed.

var getEnum = function(ordinal) {
    return keys[ordinal];
}

UPD: Is some ordinal values are absent you can use

var keys = Object.keys(enuTable).reduce(function(acc, key) {
    return acc[enuTable[key]] = key, acc;
}, {});
like image 155
Yury Tarabanko Avatar answered Oct 09 '22 01:10

Yury Tarabanko


One option would be something like the following:

 function toTableName(i) {
     for(var p in enuTable) {
         if(enuTable.hasOwnProperty(p) && enuTable[p] === i) {
              return p;
         }
     }
     throw new Error('that\'s no table...');
}
like image 24
Ben Griffiths Avatar answered Oct 09 '22 03:10

Ben Griffiths