Saturday, September 24, 2011

Enumerated Types in Java Script

Who said that JavaScript lacks enumerated types? Really it does, however due to very flexible nature of the language enums are easily done like so (example taken from ITAdapter Geometry Library):
function GeometryNamespace() //in the Geometry namespace
{
var geometry = this;
...
... ...
this.MapDirection = {
North: {Name: "North"},
NorthEast: {Name: "NorthEast"},
East: {Name: "East"},
SouthEast: {Name: "SouthEast"},
South: {Name: "South"},
SouthWest: {Name: "SouthWest"},
West: {Name: "West"},
NorthWest: {Name: "NorthWest"}
};
.............
And then later:
/** * Converts map direction to angular coordinate in radians */

this.mapDirectionToAngle = function(direction)
{
switch (direction)
{
case geometry.MapDirection.North: return 4/16 * PI2;
case geometry.MapDirection.South: return 12/16 * PI2;
case geometry.MapDirection.East: return 0.0;
case geometry.MapDirection.West: return 8/16 * PI2;
case geometry.MapDirection.NorthEast: return 2/16 * PI2;
case geometry.MapDirection.NorthWest: return 6/16 * PI2;
case geometry.MapDirection.SouthEast: return 14/16 * PI2;
case geometry.MapDirection.SouthWest: return 10/16 * PI2;
default: return 0.0;
}
}

Coming back to js enums topic, one can easily display enum as:
var dir = MapDirection.South;
var name = dir.Name; //"South"