Page 2 of 3
Adding an item
The first method we need is Add(key,item) which adds a new item under the associated key. With all collections you have to decide if you are going to allow duplicate keys but in most cases its is simpler and more logical to add the restriction that all keys are unique:
This add method returns the current count if the item has been added and undefined if the key already exists in the collection.
A remove method is just as easy to create but in this case we need to make sure that there is actually a key within the collection to be removed:
Once again the method either returns the current count of items after the removal or undefined if no item was removed. You can modify this to return the count, no matter what happens.
Notice that way that the add and remove methods automatically keep a count of the number of items in the collection. Also notice that as count is directly accessible this scheme can be defeated. If you want to protect the count then make it inaccessible and provide a getCount method.
Most collection objects also have something like an item(key) method that returns the item corresponding to the key specified. This too is easy to write:
Notice that if the key isn't in the collection the returned value is undefined.
With these methods defined you can use the collection for useful things but in most cases you would probably define additional methods.
For example a removeAll could be used to clear the collection. You could extend the definition of item to be item(key,item) and allow the user to change the item associated with the key - so creating a mutable collection.
var myCol=new Collection();
This creates a new collection and adds three items. The alert displays 3.
To see the value associated with any key you could use:
which would display 1.
To remove an item:
Now the first alert will show undefined and the count will show 2.