Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class HashNode<T> {
- constructor(public key: string, public value: T, public next: HashNode<T> | null = null) { }
- }
- export class HashTable<T> {
- private _bucketList: Array<HashNode<T> | null>;
- constructor(size: number) {
- this._bucketList = new Array<HashNode<T> | null>(size);
- }
- private hash = (key: string): number => {
- let hashCode: number = 0;
- for (let i: number = 0; i < key.length; i++) {
- hashCode += key.charCodeAt(i);
- }
- return hashCode % this._bucketList.length;
- }
- public insert = (key: string, value: T): void => {
- const index: number = this.hash(key);
- if (!this._bucketList[index])
- this._bucketList[index] = new HashNode<T>(key, value);
- else if (this._bucketList[index]!.key === key)
- this._bucketList[index]!.value = value;
- else {
- let currentNode: HashNode<T> | null = this._bucketList[index];
- while (currentNode!.next) {
- if (currentNode!.next.key === key) {
- currentNode!.next.value = value;
- return;
- }
- currentNode = currentNode!.next;
- }
- currentNode!.next = new HashNode<T>(key, value);
- }
- }
- public fetch = (key: string): T | null => {
- const index: number = this.hash(key);
- let currentNode: HashNode<T> | null = this._bucketList[index];
- while (currentNode) {
- if (currentNode.key === key) return currentNode.value;
- currentNode = currentNode.next;
- }
- return null;
- }
- public delete = (key: string): boolean => {
- const index: number = this.hash(key);
- if (!this._bucketList[index]) return false;
- else if (this._bucketList[index]!.key === key) {
- this._bucketList[index] = this._bucketList[index]!.next;
- return true;
- }
- else {
- let currentNode: HashNode<T> | null = this._bucketList[index];
- while (currentNode!.next) {
- if (currentNode!.next.key === key) {
- currentNode!.next = currentNode!.next.next;
- return true;
- }
- currentNode = currentNode!.next;
- }
- return false;
- }
- }
- }
Add Comment
Please, Sign In to add comment