export class HashTable { private readonly _table: any[]; private _size: number; constructor() { this._table = new Array(257); this._size = 0; } _hash(key: string) { let hash = 0; for (let i = 0; i < key.length; i++) { hash += key.charCodeAt(i); } return hash % this._table.length; } add(key: string, value) { const index = this._hash(key); // Initialize bucket as array if it doesn't exist if (!this._table[index]) { this._table[index] = []; } // Check if key already exists in the bucket const bucket = this._table[index]; for (let i = 0; i < bucket.length; i++) { if (bucket[i][0] === key) { // Key exists, update value bucket[i][1] = value; return; } } // Key doesn't exist, add new entry bucket.push([key, value]); this._size++; } get(key: string) { const index = this._hash(key); const bucket = this._table[index]; if (!bucket) { return null; } // Search through the bucket for the matching key for (let i = 0; i < bucket.length; i++) { if (bucket[i][0] === key) { return bucket[i][1]; } } return null; } set(key: string, value) { const index = this._hash(key); // Initialize bucket as array if it doesn't exist if (!this._table[index]) { this._table[index] = []; } const bucket = this._table[index]; // Search for existing key for (let i = 0; i < bucket.length; i++) { if (bucket[i][0] === key) { // Key exists, update value bucket[i][1] = value; return; } } // Key doesn't exist, add new entry bucket.push([key, value]); this._size++; } exists(key) { const index = this._hash(key); const bucket = this._table[index]; if (!bucket) { return false; } // Search through the bucket for the matching key for (let i = 0; i < bucket.length; i++) { if (bucket[i][0] === key) { return true; } } return false; } remove(key: string) { const index = this._hash(key); const bucket = this._table[index]; if (!bucket) { return; } // Search for the key and remove it for (let i = 0; i < bucket.length; i++) { if (bucket[i][0] === key) { bucket.splice(i, 1); this._size--; // Clean up empty bucket if (bucket.length === 0) { this._table[index] = undefined; } return; } } } list() { const result: any[] = []; for (let i = 0; i < this._table.length; i++) { const bucket = this._table[i]; if (bucket) { for (let j = 0; j < bucket.length; j++) { result.push({ key: bucket[j][0], value: bucket[j][1], }); } } } return result; } count() { return this._size; } }