Guest User

Untitled

a guest
Aug 31st, 2017
37
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.26 KB | None | 0 0
  1. function HashTable(size) {
  2. this.buckets = Array(size);
  3. this.numBuckets = this.buckets.length;
  4. }
  5.  
  6. function HashNode(key, value, next) {
  7. this.key = key;
  8. this.value = value;
  9. this.next = next || null
  10. }
  11.  
  12. HashTable.prototype.hash = function(key) {
  13. var total = 0;
  14. for (var i = 0; i < key.length; i++) {
  15. total += key.charCodeAt(i);
  16. }
  17. var bucket = total % this.numBuckets;
  18. return bucket;
  19. };
  20.  
  21.  
  22. HashTable.prototype.insert = function(key, value) {
  23. var index = this.hash(key);
  24. // console.log('INDEX', index);
  25. if (!this.buckets[index]) {
  26. this.buckets[index] = new HashNode(key, value);
  27. }
  28. else if (this.buckets[index].key === key) {
  29. this.buckets[index].value = value;
  30. }
  31. else {
  32. var currentNode = this.buckets[index];
  33. while (currentNode.next) {
  34. if(currentNode.next.key === key) {
  35. currentNode.next.value = value;
  36. return;
  37. }
  38. currentNode = currentNode.next;
  39. }
  40. currentNode.next = new HashNode(key, value);
  41. }
  42. }
  43.  
  44.  
  45.  
  46. HashTable.prototype.get = function(key) {
  47. var index = this.hash(key);
  48. if (!this.buckets[index]) return null;
  49. else {
  50. var currentNode = this.buckets[index];
  51. while (currentNode) {
  52. if (currentNode.key === key) return currentNode.value;
  53. currentNode = currentNode.next;
  54. }
  55. return null;
  56. }
  57. };
  58.  
  59.  
  60. HashTable.prototype.retrieveAll = function() {
  61. var allNodes = [];
  62. for (var i = 0; i < this.numBuckets; i++) {
  63. var currentNode = this.buckets[i];
  64. while(currentNode) {
  65. allNodes.push(currentNode)
  66. currentNode = currentNode.next;
  67. }
  68. }
  69. return allNodes;
  70. }
  71.  
  72.  
  73.  
  74. var myHT = new HashTable(30);
  75. //myHT.hash('Becca')
  76. //console.log(myHT);
  77.  
  78.  
  79. myHT.insert('Dean', 'dean@gmail.com');
  80. myHT.insert('Megan', 'megan@gmail.com');
  81. myHT.insert('Dane', 'dane@yahoo.com');
  82. myHT.insert('Dean','deanmachine@gmail.com');
  83. myHT.insert('Megan', 'megansmith@gmail.com');
  84. myHT.insert('Dane', 'dane1010@outlook.com');
  85. myHT.insert('Joe', 'joey@facebook.com');
  86. myHT.insert('Samantha', 'sammy@twitter.com')
  87.  
  88. console.log(myHT.retrieveAll())
  89.  
  90. //console.log(myHT.buckets)
  91.  
  92. console.log(myHT.get('Dane'))
  93.  
  94.  
  95. //HASH TABLE have O(1) insertion and lookup
Add Comment
Please, Sign In to add comment