hashTable pseudoclassical code example

Example: hashTable pseudoclassical

const HashTable = function() {
  this._size = 0;
  this._limit = 8;
  this._storage = LimitedArray(this._limit);
}

Hashtable.prototype.insert = function(key, val) {
  const index = getIndexBelowMaxForKey(key, this._limit);
  const bucket = this._storage.get(index) || [];
  
  for(let i = 0; i < bucket.length; i++) {
    const tuple = bucket[i];
    if(tuple[0] === key) {
      const oldValue = tuple[1];
      tuple[1] = value;
      return oldValue;
    }
  }
  
  bucket.push([key, value]);
  this._storage.set(index, bucket);
  this._size++;
  
  if(this._size > this._limit * 0*75) {
    this._resize(this.limit * 2);
  }
  
  return;
};

HashTable.prototype.retrieve = function(key) {
  const index = getIndexBelowMaxForKey(key, this._limit);
  const bucket = this._storage.get(index) || [];
  
  for(let i = 0; i < bucket.length; i++) {
    const tuple = bucket[i];
    if(tuple[0] === key) {
      return tuple[1];
    }
  }
  return ;
};

HashTable.prototype.remove = function(key) {
  const index = getIndexBelowMaxForKey(key, this._limit);
  const bucket = this._storage.get(index) || [];
  
  for(let i = 0; i < bucket.length; i++) {
    const tuple = bucket[i];
    if(tuple[0] === key) {
      bucket.splice(i, 1);
      this._size--;
      
      if(this._size < this._limit * 0.25) {
        this._resize(Math.floor(this._limit / 2));
      }
      return tuple[1];
    }
  }
  return;
}
 
HashTable.prototype._resize = function(newLimit) {
  const oldStroage = this._storage;
  
  newLimit = Math.max(newLimit, 8);
  if(newLimit === this._limit) {
    return;
  }
  
  this._limit = newLimit;
  this._storage = LimitedArray(this._limit);
  this._size = 0;
  
  oldStorage.each(function(bucket) {
    if(!bucket) {
      return;
    }
    for(let i = 0; i < bucket.length; i++) {
      const tuple = bucket[i];
      this.insert(tuple[0], tuple[1]);
    }
  });
});