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 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;
}, {});
                        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...');
}
                        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