Advertisement
Guest User

Untitled

a guest
Apr 25th, 2019
106
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.97 KB | None | 0 0
  1. const HashTable = function() {
  2. this._limit = 8;
  3. this._size = 0;
  4. this._storage = LimitedArray(this._limit)
  5. }
  6.  
  7. HashTable.prototype.insert = function(key, value) {
  8. let index = getIndexBelowMaxForKey(key, this._limit);
  9.  
  10. const innerBuckets = [];
  11. const innerTuples = {};
  12. innerTuples[key] = value;
  13. this._size++;
  14.  
  15. if (this._size > this._limit * 0.7) {
  16. this.resize(this._limit * 2)
  17. index = getIndexBelowMaxForKey(key, this._limit)
  18. }
  19.  
  20. if (this._storage.get(index) === undefined) {
  21. innerBuckets.push(innerTuples)
  22. this._storage.set(index, innerBuckets)
  23. } else {
  24. for (let i = 0; i < this._storage.get(index).length; i++) {
  25. if (this._storage.get(index)[i][k]) {
  26. this._storage.get(index)[i][k] = v
  27. } else {
  28. this._storage.get(index).push(innerTuples)
  29. }
  30. }
  31. }
  32. }
  33.  
  34. HashTable.prototype.retrieve = function (key) {
  35. const index = getIndexBelowMaxForKey(key, this._limit)
  36.  
  37. for (let i = 0; i < this._storage.get(index).length; i++) {
  38. if (this._storage.get(index)[i] === undefined) {
  39. return undefined
  40. } else if (this._storage.get(index)[i][key]) {
  41. return this._storage.get(index)[i][key]
  42. }
  43. }
  44. }
  45.  
  46. HashTable.prototype.remove = function (key) {
  47. let index = getIndexBelowMaxForKey(key, this._limit)
  48.  
  49. this._size--
  50. if (this._size < this._limit * 0.3) {
  51. this.resize(this._limit / 2)
  52. index = getIndexBelowMaxForKey(key, this._limit)
  53. }
  54.  
  55. for (let i = 0; i < this._storage.get(index).length; i++) {
  56. if (this._storage.get(index)[i][key]) {
  57. delete this._storage.get(index)[i]
  58. }
  59. }
  60. }
  61.  
  62. HashTable.prototype.resize = function (newLimit) {
  63. this._limit = newLimit
  64. let oldStorage = this._storage
  65. this._storage = LimitedArray(this._limit)
  66.  
  67. oldStorage.each((pairs) => {
  68. if (pairs) {
  69. for (var i = 0; i < pairs.length; i++) {
  70. if (pairs[i]) {
  71. let pair = pairs[i]
  72. this.insert(Object.keys(pair)[0], Object.values(pair)[0])
  73. this._size--
  74. }
  75. }
  76. }
  77. })
  78. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement