Logic problem (javascript)

Discussion in 'JavaScript' started by falconlee, Jun 11, 2009.

  1. #1
    I wish to trace the last checked check box, but face this logic problem, cannot get the expected output...Any idea?

    my logic:
    - max check box on a page is 10, so i set max length as 10.
    - when user is checked the check box get the value and store into an array.
    - first time user checked store a value, when second time check(means is unchecked), so the value will be deleted from the array, so i must do the
    checking first.
    - if user unchecked, i'll delete an element in an array, then do shifting (if next element is exist).
    - count as an counter, would not more than max length
    - round is to trace whether current value is same in the array, if no, then add the element into an array.

    correct me if i'm wrong and give me some suggestion..thanks

    var checkedHistory = new Array();
    var maxlength = 10;
    var count=0;
    var round=0;
    function traceChecked(value)
    {
    if(checkedHistory[0] == null){
    checkedHistory[0] = value;
    count++;

    }else{
    for(var i=0; i<count; i++){
    if(checkedHistory == value){// perform data redundancy checking
    checkedHistory.splice(i,1); // delete redundancy data

    if(count == 1){
    count--;

    }else{
    if(checkedHistory[i+1] == null){
    count--;

    }else{
    checkedHistory == checkedHistory[i+1]; //do shifting
    count--;

    }
    }
    }
    round++;
    }

    if(round == count-1){
    checkedHistory[round] = value;
    count++;

    }

    }

    if(count > maxlength){
    count=0;
    }

    }
     
    falconlee, Jun 11, 2009 IP
  2. yoavmatchulsky

    yoavmatchulsky Member

    Messages:
    57
    Likes Received:
    3
    Best Answers:
    0
    Trophy Points:
    48
    #2
    this is what i came up with:

    var counter = 0;
    var checkedArray = {};
    
    function traceChecked(value)
    {
      // check if the value exists in the array
      var exists = typeof(checkedArray[value]) != 'undefined' && checkedArray[value] == true;
      
      // do the action
      if (exists)
      {
        delete checkedArray[value];
        counter--;
      }
      else
      {
        if (counter < maxValue)
        {
          checkedArray[value] = true;
          counter++;
        }
      }
    }
    Code (markup):
    i created the 'checkedArray' as an object (which is a hashtable, not an array). that means that every checkedArray[value] lookup is O(1).
    First i check if the value exists as a property in the object and that its really true, and then i update the object and counter accordingly.
     
    yoavmatchulsky, Jun 12, 2009 IP