Advertisement
Guest User

Untitled

a guest
Feb 19th, 2017
114
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.31 KB | None | 0 0
  1. // Hash Table
  2. // key value pairs
  3. // {key: name, value: number}
  4. // constructor function for the table and consturctor function for the node
  5.  
  6. function HashTable(size) {
  7. // make a new array of size of choice and assign it to property of buckets
  8. this.buckets = Array(size);
  9. this.numBuckets = this.buckets.length;
  10. }
  11.  
  12. function HashNode(key, value, next) {
  13. this.key = key;
  14. this.value = value;
  15. this.next = next || null;
  16. }
  17.  
  18. HashTable.prototype.hash = function(key) {
  19. var total = 0;
  20. for (var i = 0; i < key.length; i++) {
  21. total += key.charCodeAt(i);
  22. }
  23. var bucket = total % this.numBuckets;
  24. return bucket;
  25. };
  26.  
  27.  
  28.  
  29. // console.log(myHT);
  30. // console.log(myHT.hash('Becca'));
  31. // console.log(myHT);
  32.  
  33. // insert method
  34. // takes key/value pair and turns into a hash node then placed into correct bucket
  35.  
  36. HashTable.prototype.insert = function(key, value) {
  37. var index = this.hash(key);
  38. if(!this.buckets[index]) {
  39. this.buckets[index] = new HashNode(key, value);
  40. } else {
  41. var currentNode = this.buckets[index];
  42. while(currentNode.next) {
  43. currentNode = currentNode.next;
  44. }
  45. currentNode.next = new HashNode(key, value);
  46. }
  47.  
  48. };
  49.  
  50. var myHT = new HashTable(30);
  51. myHT.insert('Dean', 'dean@gmail.com');
  52. myHT.insert('Meagan', 'meagan@gmail.com');
  53. myHT.insert('Dane', 'dane@yahoo.com');
  54.  
  55. console.log(myHT.buckets);
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement