Skip to content

Instantly share code, notes, and snippets.

@OneCent01
Last active January 21, 2019 08:07
Show Gist options
  • Save OneCent01/7a6ea101e35cf628e0edce5b1f6a98ad to your computer and use it in GitHub Desktop.
Save OneCent01/7a6ea101e35cf628e0edce5b1f6a98ad to your computer and use it in GitHub Desktop.
Javascript implementation of an insert value method for hashtables
HashTable.prototype.add = function(key, value) {
var index = key.hashCode();
var tuple = [key, value];
var bucket = this._storage.get(index);
if (bucket) {
for (var i = 0; i < bucket.length; i++) {
if (bucket[i][0] === key) {
bucket[i][1] = value;
} else {
bucket.push(tuple);
}
}
} else {
this._storage.set(index, [tuple]);
}
};
@srehaider
Copy link

srehaider commented Jan 21, 2019

There is a bug in this code, when a bucket is found at given index you iterate over bucket check for current key, if you find a key than you update value and keep iterating over bucket and if key is not found you push tuple in array and keep iterating, for each iteration if no key is found tuple will be pushed to array...
It should be like this.

HashTable.prototype.add = function(key, value) {
  var index = key.hashCode();
  var tuple = [key, value];
  var bucket = this._storage.get(index);
  if (bucket) {
    for (var i = 0; i < bucket.length; i++) {
      if (bucket[i][0] === key) {
        bucket[i][1] = value;
        return;
      }
    }
    bucket.push(tuple);
  } else {
    this._storage.set(index, [tuple]);
  } 
};

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment