javascript2016
javascript2016

Reputation: 1013

data structure - how to implement hash tables (including association lists) in javascript?

I am working on a hash table /data structure exercise but dont understand it quite well. Each data has to be an instance of the list 'List' and using athe hash function, I need to add key /value pairs to the correct list and return the items based on their key. As what I tried so far doesnt work, any help or explanation why what I have so far doesnt work would be much appreciated! Thank you!

function List () {
  this.head=null;
}
function ListN (key, value, next) {
  this.key = key;
  this.value = value;
  this.next = next;
}
List.prototype.set = function (key, value) {
 var newNode=new ListN(key, value, this.head);
  this.head=newNode;
};

List.prototype.get = function (key) {
  var node = this.head;
    while (node) {
       if (node.key === key) {
        return node.value;
       }
        node = node.next;
    }
};
  smallList = new List();

function HashT () {
  this.data = Array(30);
}

HashT.prototype.set = function (key, value) {
  var index=hash(key);
  if (!this.data[index]) {
    this.data[index]=new List();
  }

  this.data[index].set({key:key, value:value});
};

HashT.prototype.get = function (key) {
var index=hash(key);
return this.data[index];

};

Upvotes: 0

Views: 582

Answers (1)

Patrick Roberts
Patrick Roberts

Reputation: 51916

The problem is simple, your mistake is here:

this.data[index].set({key:key, value:value});

It needs to be changed to

this.data[index].set(key, value);

In your HashT.prototype.get, the return statement needs to be:

return this.data[index].get(key);

Upvotes: 1

Related Questions