Example: An Extensible switch Function
The switch statement of Chapter 11 is one of the statements I like. It allows me to compare an unknown value against a set of known values, and at the first match, execute a code block. This makes it a very powerful feature of the language. The only thing I don't like about it is the inability to add new known values to the set of known values it checks against. I would have to replace the function containing the switch statement with another function or edit the function's source code (see Chapter 2's example for details on this). Either way is a bit long for simply adding one more known value.
Enter arrays. As you know, arrays can handle any kind of object or literal value you throw at them in an element list. So suppose I have a list of known values in an array to check an unknown value against, and a code block to execute for each match. Then it's merely a matter of checking each element in the array until I have a match, and if there is no match, executing the default code.
The xswitch() script, which I provide here as Listing 3.7, does precisely this. The xSwitchObj() function creates the array and attaches a few methods for accessing the array. The xswitch() function returns a code block, which you can use an eval() method call to execute. Basically, the results have the same scope as a switch statement would have, but also thanks to the object-oriented design they support the capability to add new cases as the user sees fit.
Listing 3.7 The xswitch() Script with a Sample Use
Using the xswitch function is actually fairly easy. You start by defining a basic xswitchObj() object.
myCases = new xswitchObj()
This is not muchbut I can define a default case for the new xswitchObj() object easily:
Adding individual cases to read before the default is equally easy:
myCases.addCase(1, "alert('one')") myCases.addCase(2, "alert('two')")
Then, to actually execute the xswitch() as intended, I simply call an eval() of the xswitch() function, with the first argument being the unknown value mentioned previously, and the second being the xSwitchObj() object it is being compared against:
eval(xswitch(3, myCases)) // executes "alert('default case')" and pops up an alert
The xswitch() function searches the element list of the xswitchObj() array passed to it for the matching value in one of its properties. At the first match, it returns the code and breaks out of the loop. The default case reflects here because no case has been defined for the number 3. This, however, is easily solved:
This time, when you call
the eval() method receives "alert('three')", which it then executes.