Collection objects or, as they are called in Perl, associative arrays, provide a method of storing and retrieving items in memory based upon a key in a data structure that stores pairs of keys and values. A value may be inserted or retrieved based on its unique key. This key-value pair makes collections particularly useful in lookups. In addition, the uniqueness of the key provides the ability to tally keys or to determine if keys are actually unique.
Looking to VBScript as a model
When coding in server-side VBScript, I often use a collection object for routine tasks, such as managing a small database. For example, imagine two database tables. The first table stores a list of available parts sold by a company, while the second table lists manufacturing locations. See Figure A.
Let’s say that you must create a Web-based report that consists of part number, part description, and factory name. You might craft a SQL statement like the one in Listing A.
Seems simple enough, right? But suppose that for some reason, you already have the needed part table information in an ADO recordset. For example, maybe the part table information was used to produce a commissions report. What do you do now? You could use the above SELECT anyway or loop through the part recordset and perform a SELECT statement for each part to get the factory name. Either option would work, but accessing a storage device is one of the most time-consuming things a script can do. In times like these, what I normally do is write a SELECT statement to get both the factory number and name, as shown in Listing B.
Because of its ease of use, I chose the dictionary object from VBScript to use as a model to implement the methods shown in Table A.
To write a constructor, you use the this keyword to refer to the created object’s properties and methods. The constructor’s job is to initialize the object, properties, and methods. In the case of our collection object, there are three properties: this.objCollection, this.count, and this.error. The code snippet in Listing C illustrates how the definition of the properties would appear.
In addition to these three properties, the collection object has six methods: this.add, this.exists, this.item, this.removeAll, this.remove, and this.keys. The definitions of these methods are similar to those of the properties, with one difference: The purpose of the methods is to expose functions. So in the case of the add method, you need the code in Listing D.
var colFactory = new collection(); // Create an instance
Once an instance of the collection object is created, using it is a simple matter of adding item pairs. Returning to the previous reporting example, populating the collection can be accomplished through the use of a few lines of code like those shown in Listing E.
You can retrieve the name associated with a factory number with one line:
strFactoryName = colFactory.item(strFactoryNumber);