Guest User

Untitled

a guest
Jan 12th, 2018
346
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.74 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. HashTable.prototype.insert = function(key, value) {
  22. var index = this.hash(key);
  23. if (!this.buckets[index]) {
  24. this.buckets[index] = new HashNode(key, value);
  25. } else if (this.buckets[index].key === key) {
  26. this.buckets[index].value = value;
  27. } else {
  28. var currentNode = this.buckets[index];
  29. while (currentNode.next) {
  30. if (currentNode.next.key === key) {
  31. currentNode.next.value = value;
  32. return;
  33. }
  34. currentNode = currentNode.next;
  35. }
  36. currentNode.next = new HashNode(key, value);
  37. }
  38. };
  39.  
  40. HashTable.prototype.get = function(key) {
  41. var index = this.hash(key);
  42. if (!this.buckets[index]) return null;
  43. else {
  44. var currentNode = this.buckets[index];
  45. while (currentNode) {
  46. if (currentNode.key === key) {
  47. return currentNode.value;
  48. }
  49. currentNode = currentNode.next;
  50. }
  51. return null;
  52. }
  53. };
  54.  
  55. HashTable.prototype.retrieveAll = function() {
  56. var allNodes = [];
  57. for (var i = 0; i< this.numBuckets; i++) {
  58. var currentNode = this.buckets[i];
  59. while (currentNode) {
  60. allNodes.push(currentNode);
  61. currentNode = currentNode.next;
  62. }
  63. }
  64. return allNodes;
  65. };
  66.  
  67. var ht = new HashTable(30);
  68. ht.insert('Rebecca', 'rebecca@gmail.com');
  69. ht.insert('Dean', 'dean@gmail.com');
  70. ht.insert('Bob', 'bob@gmail.com');
  71. ht.insert('Dean', 'dean2@gmail.com');
  72.  
  73. console.log(ht.retrieveAll());
Add Comment
Please, Sign In to add comment