Sets in Javascript

May 11, 2005

When working with XML one regularly needs to test whether a node has a certain node type. Usually the question is if the type of the node is one of a number of types. For instance one can only set the node value on attributes, text nodes, cdata sections, processing instructions and comments. In javascript there are a lot of ways to perform this test, most of them awkward:

  var typeInSet;
  switch (nodeType)
  {
    case 2:
    case 3:
    case 4:
    case 7:
    case 8:
      typeInSet = true;
      break;
    default:
      typeInSet = false;
      break;
  }

Or:

  var typeInSet = nodeType == 2 || nodeType == 3 || nodeType == 4 || nodeType == 7 || nodeType == 8;

But the flexibility of javascript allows you to make this statement a lot more readable by introducing the concept of a set:

  var typeInSet = nodeType in set(2, 3, 4, 7, 8);

In this example the javascript in operator is used in combination with a function set that converts its arguments to an object. The implementation of set is trivial:

  function set ()
  {
    var result = {};

    for (var i = 0; i < arguments.length; i++)
      result[arguments[i]] = true;

    return result;
  }