Pages

Thursday, December 30, 2010

Grouping Algorithm Using Javascript

/**
 * @author  : irfanudin ridho
 * @email   : irfan.ub@gmail.com
 * @date    : December 29,2010
 * @version : 1.0
 *
 * This function will provide distinct selection algorithm.
 */

/**
 * Constructor service
 * @param data array of data
 */
function GroupingAlgorithm(data){
    this.data = data;
}

/**
 * a mehtod that provide base service to slice the data.
 * var data = [1,2,2,3,1,2]
 *          = [2,2,3,2]
 *          = [3]
 *          = []
 * @param varData array of data
 * @return sliced array
 */
GroupingAlgorithm.prototype.first = function(varData){
    var value = varData[0];
    var newData = new Array();
    var k = 0;
    for(i=1;i<varData.length;i++){
        if(varData[i]!=value){
            newData[k]=varData[i];
            k++;
        }
    }
    return newData;
};


/**
 * This function will do like what happend at SELECT DISTINCT 
 * in MySQL.
 * @return array unsorted distinct value;
 */
GroupingAlgorithm.prototype.getDistinctValue = function(){
    var rest = true;
    var distinctValue = new Array();
    var d = 0;
    var copyData = this.data;
    while(rest){
        distinctValue[d]=copyData[0];
        copyData = this.first(copyData);
        d++;
        if(copyData.length==0){
            rest = false;
        }

    }
    return distinctValue;
};

/**
 * A method to know how many occurence for specified value
 *
 * @return array of data
 */
GroupingAlgorithm.prototype.getTotalNumber = function(){
    var distinctData = this.getDistinctValue();
    var nTimes = new Array();
  
    for(i=0;i<distinctData.length;i++){
        var n = 0;
        for(j=0;j<this.data.length;j++){
            if(distinctData[i]==this.data[j]){
                n++;
            }
        }
        nTimes[i]=n;
    }
    return nTimes;
};
        

No comments:

Post a Comment