Create a Hash Table help

the remove method is not working ,I don’t know what 's wrong ,please help me out

var called = 0;
var hash = (string) => {
  called++;
  var hash = 0;
  for (var i = 0; i < string.length; i++) { hash += string.charCodeAt(i); }
  return hash;
};
var HashTable = function() {
  let size=8;
  this.collection = {};
  // change code below this line
  this.add=function(key,value){
    let index=hash(key)%size;
    let val=false;
    if(index in this.collection){
      for(let i=0;i<this.collection[index].length;i++){
        if(this.collection[index][i][0]==key){
          this.collection[index][i][1]=value;
          val=true;
        }
      }
      if(val==false){
        this.collection[index].push([key,value]);
      }
    }
    else {
      this.collection[index]=[[key,value]];
    }
  }
  this.remove=function(key){
    let index=hash(key)%size;
    if(index in this.collection){
      if(this.collection[index].length==1 && this.collection[index][0][0]==key){
         delete this.collection[index];
         return this.collection;
      }
      else {
        for(let i=0;i<this.collection[index].length;i++){
          if(this.collection[index][i][0]===key){
             this.collection[index].splice(i,1);  
             return this.collection;   
          }
        }
      }
    }
    else {
      return undefined;
    }
  }
  this.lookup=function(key){
      let index=hash(key) % size;
    if(index in this.collection){
        if(this.collection[index].length==1){
           return this.collection[index][0][1];
        }
        else {
          for(let i=0;i<this.collection[index].length;i++){
            if(this.collection[index][i][0]===key){
             return this.collection[index][i][1];
            }
          }
        }
  }
  else {
    return undefined;
  }
  }
  // change code above this line
};

https://learn.freecodecamp.org/coding-interview-prep/data-structures/create-a-hash-table

1 Like

Just copied and pasted your code into the challenge and it passed all the tests.

Sometimes it’s worth testing your code yourself and see if you get the desired results. Also, pay attention to the tests’ descriptions. Sometimes it just a detail you’ve forgotten (not in this case though).

If you see your code works as required by the tests but they keep failing, move on. FCC tests can be quite buggy sometimes since descriptions not always (almost never) reflects perfectly the tests that are being made. The challenges are there to teach you more than anything else. So don’t obsess about getting all tests passing every time.

I am guessing at the time the user submitted the code for the challenge, maybe one of the tests had a bug in it. You will notice, the original post is about 13 months old.

1 Like