Will
Cannings

JavaScript has (for better or worse) few structures that some procedural and OOP languages have, e.g Classes, Enumerations (Enums), etc. Some of this comes from its Functional programming roots, and some from its Prototype object model. All in all I personally feel it works really well, and is a nice break from more traditional programming. But sometimes an old school programming structure is called for.

In a web app I’m writing, we have objects that are sent verbatim over JSON from a Database record. One of the attributes is an integer field representing the ‘type’ of the record (limited to the values from an enum we fake using Tuples in Python). When it came time to create the edit screen for these objects, it was obvious it would be nice to represent the possible values of this attribute in an enum JS side as well.

To do this we took advantage of the arguments variable accessible from within functions. All JS functions can be called with as few or as many arguments as you want – any missing arguments are passed to the function as ‘undefined’; extra arguments are available through the arguments variable. Because functions are represented as Function objects which have a length property, you can easily retrieve the number of parameters to a function:

> fn = function(a,b) {}
> a.length
2

We can use the arguments variable to create Enumerations very easily.

function Enumeration() {
  this.allItems = [];
  for(var i = 0; i < arguments.length; i++) {
    name = arguments[i];
    this[name] = i;
    this[i] = name;
    this.allItems.push(name)
  }
}

This constructor function can then be used like this:

> var types = new Enumeration('show', 'new', 'edit', 'create', 'update', 'destroy')
> types[0]
show
> types['show']
0
> types.allItems.each(function(item) {console.log(item)})
index
show
new
edit
create
update
destroy

The types object can be used as a lookup both through the Enumerations values (0-6) and the keys or names of the values (‘index’ – ‘destroy’). For easy iteration over the values of the Enumeration, the allItems property is an array of the values (we use this to construct a select tag for choosing between the different values).