Javascript Enum To Corresponding String Value
For TypeScript, there is a simpler solution (Please ignore my answer if you stick with JS):
export enum Direction {
none,
left = 1,
right = 2,
top = 4,
bottom = 8
}
export namespace Direction {
export function toString(dir: Direction): string {
return Direction[dir];
}
export function fromString(dir: string): Direction {
return (Direction as any)[dir];
}
}
console.log("Direction.toString(Direction.top) = " + Direction.toString(Direction.top));
// Direction.toString(Direction.top) = top
console.log('Direction.fromString("top") = ' + Direction.fromString("top"));
// Direction.fromString("top") = 4
console.log('Direction.fromString("xxx") = ' + Direction.fromString("unknown"));
// Direction.fromString("xxx") = undefined
Because the enumeration type is compiled into an object(dictionary). You don't need a loop to find the corresponding value.
enum Direction {
left,
right
}
is compiled into:
{
left: 0
right: 1
0: "left",
1: "right"
}
Do you actually need the numeric values at all? If not then you could use something like this:
var TEST_ERROR = {
SUCCESS : 'Success',
FAIL : 'Fail',
ID_ERROR : 'ID Error'
};
Not quite optimal, but the cleanest you can get without pre-computing the reverse dictionary (and besides, this shouldn't be too much of an issue if you only have a few enumeration values):
function string_of_enum(enum,value)
{
for (var k in enum) if (enum[k] == value) return k;
return null;
}