fueanta

Hash Table in Typescript.

May 27th, 2020
108
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. class HashNode<T> {
  2.     constructor(public key: string, public value: T, public next: HashNode<T> | null = null) { }
  3. }
  4.  
  5. export class HashTable<T> {
  6.     private _bucketList: Array<HashNode<T> | null>;
  7.  
  8.     constructor(size: number) {
  9.         this._bucketList = new Array<HashNode<T> | null>(size);
  10.     }
  11.  
  12.     private hash = (key: string): number => {
  13.         let hashCode: number = 0;
  14.         for (let i: number = 0; i < key.length; i++) {
  15.             hashCode += key.charCodeAt(i);
  16.         }
  17.         return hashCode % this._bucketList.length;
  18.     }
  19.  
  20.     public insert = (key: string, value: T): void => {
  21.         const index: number = this.hash(key);
  22.         if (!this._bucketList[index])
  23.             this._bucketList[index] = new HashNode<T>(key, value);
  24.         else if (this._bucketList[index]!.key === key)
  25.             this._bucketList[index]!.value = value;
  26.         else {
  27.             let currentNode: HashNode<T> | null = this._bucketList[index];
  28.             while (currentNode!.next) {
  29.                 if (currentNode!.next.key === key) {
  30.                     currentNode!.next.value = value;
  31.                     return;
  32.                 }
  33.                 currentNode = currentNode!.next;
  34.             }
  35.             currentNode!.next = new HashNode<T>(key, value);
  36.         }
  37.     }
  38.  
  39.     public fetch = (key: string): T | null => {
  40.         const index: number = this.hash(key);
  41.         let currentNode: HashNode<T> | null = this._bucketList[index];
  42.         while (currentNode) {
  43.             if (currentNode.key === key) return currentNode.value;
  44.             currentNode = currentNode.next;
  45.         }
  46.         return null;
  47.     }
  48.  
  49.     public delete = (key: string): boolean => {
  50.         const index: number = this.hash(key);
  51.         if (!this._bucketList[index]) return false;
  52.         else if (this._bucketList[index]!.key === key) {
  53.             this._bucketList[index] = this._bucketList[index]!.next;
  54.             return true;
  55.         }
  56.         else {
  57.             let currentNode: HashNode<T> | null = this._bucketList[index];
  58.             while (currentNode!.next) {
  59.                 if (currentNode!.next.key === key) {
  60.                     currentNode!.next = currentNode!.next.next;
  61.                     return true;
  62.                 }
  63.                 currentNode = currentNode!.next;
  64.             }
  65.             return false;
  66.         }
  67.     }
  68. }
RAW Paste Data