Guest User

Untitled

a guest
Oct 17th, 2017
419
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.00 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.  
  13. HashTable.prototype.hash = function(key){
  14. var total = 0;
  15. for (var i=0; i<key.length; i++){
  16. total+=key.charCodeAt(i);
  17. }
  18. var bucket = total % this.numBuckets;
  19. return bucket;
  20. }
  21.  
  22.  
  23. HashTable.prototype.insert = function(key, value){
  24. var index =this.hash(key);
  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. return;
  31. }
  32. else{
  33. var currentNode = this.buckets[index];
  34. while(currentNode.next){
  35. if(currentNode.key===key){
  36. currentNode.value=value;
  37. return;
  38. }
  39. if(currentNode.next.key===key){
  40. currentNode.next.value = value;
  41. return;
  42. }
  43. currentNode = currentNode.next;
  44. }
  45. currentNode.next = new HashNode(key, value);
  46. }
  47. }
  48.  
  49.  
  50. HashTable.prototype.get=function(key){
  51. var index = this.hash(key);
  52. if(!this.buckets[index]) return null;
  53. else{
  54. var currentNode = this.buckets[index];
  55. while(currentNode){
  56. if(currentNode.key===key) return currentNode.value;
  57. currentNode = currentNode.next;
  58. }
  59. }
  60. return null;
  61. }
  62.  
  63.  
  64.  
  65. HashTable.prototype.retrieveAll = function(){
  66. var theList = [];
  67. var i;
  68. for(i=0; i<this.numBuckets; i++){
  69. currentNode = this.buckets[i];
  70. while(currentNode){
  71. theList.push(currentNode);
  72. currentNode = currentNode.next;
  73. }
  74. }
  75. return theList;
  76. }
  77.  
  78.  
  79.  
  80.  
  81.  
  82.  
  83.  
  84.  
  85.  
  86.  
  87.  
  88.  
  89. var myHT = new HashTable(30);
  90. myHT.insert('Dean','dean@gmail.com');
  91. myHT.insert('Megan','megan@gmail.com');
  92. myHT.insert('Daen','deneme@gmail.com');
  93. myHT.insert('Dean','testtest@gmail.com');
  94.  
  95. // console.log(myHT.buckets);
  96.  
  97. // console.log(myHT.get('Dean'));
  98.  
  99. console.log(myHT.retrieveAll());
Add Comment
Please, Sign In to add comment