Pages

Thursday, December 30, 2010

List In Javascript

/**
 * A List of ADT. This ADT works well like list in other library.
 *
 * @author  : irfanudin ridho
 * @email   : irfan.ub@gmail.com
 * @date    : December 31, 2010
 * @version : 1.0
 */

/**
 * Constructor service
 */
function List(){
    this.data = new Array();
}

/**
 * method to add an element to list
 *
 * @param item string,number,boolean value. element to be added
 */
List.prototype.add = function(item){
    var len = this.data.length;
    this.data[len] = item;
};

/**
 * method to remove an element from the list
 *
 * @param item string, number or boolean as what the list contains.
 */
List.prototype.remove = function(item){
    var newData = new Array();
    var len = this.data.length;
    var k = 0;
    for(i=0;i<len;i++){
        if(this.data[i]!=item){
            newData[k] = this.data[i];
            k++;
        }
    }
    this.data = newData;
};


/**
 * method to know how many elements in the list
 *
 * @return number number of elements
 */
List.prototype.size = function(){
    return this.data.length;
};

/**
 * method to give this list as an array
 *
 * @return an array
 */
List.prototype.toArray = function(){
    return this.data;
};
      

No comments:

Post a Comment