Javascript data structures - a collection object
Thursday, 28 October 2010
Article Index
Javascript data structures - a collection object
Managing the collection
Enumerators

 

Banner

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=function(key,item)
{
if(this.collection[key]!=undefined)
return undefined;
this.collection[key]=item;
return ++this.count
}

This add method returns the current count if the item has been added and undefined if the key already exists in the collection.

 

Remove method

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:

this.remove=function(key)
{
if(this.collection[key]==undefined)
return undefined;
delete this.collection[key]
return --this.count
}

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.

Item key

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:

this.item=function(key)
{
return this.collection[key];
}

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.

For example:

var myCol=new Collection();
myCol.add("A",0);
myCol.add("B",1);
myCol.add("C",2);
alert(myCol.count);

This creates a new collection and adds three items. The alert displays 3.

To see the value associated with any key you could use:

alert(myCol.item("B"));

which would display 1.

To remove an item:

myCol.remove("C");
alert(myCol.item("C"));
alert(myCol.count);

Now the first alert will show undefined and the count will show 2.

 

Banner

<ASIN:059680279X>

<ASIN:0980285801>

<ASIN:0273721534>



Last Updated ( Tuesday, 15 January 2013 )
 
 

   
RSS feed of all content
I Programmer - full contents
Copyright © 2014 i-programmer.info. All Rights Reserved.
Joomla! is Free Software released under the GNU/GPL License.