-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathhashTable.ts
66 lines (58 loc) · 1.88 KB
/
hashTable.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
import {SinglyLinkedListForHash} from "../singly-linked-list/singlyLinkedList";
const defaultHashTableSize = 32
export class HashTable {
buckets: SinglyLinkedListForHash<{ key: string, value: string }>[]
constructor(hashTableSize = defaultHashTableSize) {
this.buckets = Array(hashTableSize).fill(null);
}
// hash function
hash(key: string): number {
const hash = Array.from(key).reduce(
(hashAccumulator, keySymbol) => (hashAccumulator + keySymbol.charCodeAt(0)),
0,
);
return hash % this.buckets.length;
}
// add
add(key: string, value: string) {
const keyHash = this.hash(key)
if (!this.buckets[keyHash]) {
let newLinkedList = new SinglyLinkedListForHash<{ key: string, value: string }>()
newLinkedList.append({key, value})
this.buckets[keyHash] = newLinkedList
} else {
let bucketLinkedList = this.buckets[keyHash]
let node = bucketLinkedList.find({key})
if (node) {
node.value.value = value
} else {
bucketLinkedList.append({key, value})
}
}
}
// get
find(key: string): string {
const keyHash = this.hash(key)
if (!this.buckets[keyHash]) {
return null
} else {
let bucketLinkedList = this.buckets[keyHash]
let node = bucketLinkedList.find({key})
if (node) {
return node.value.value
} else {
return null
}
}
}
// delete
delete(key: string) {
const keyHash = this.hash(key);
const bucketLinkedList = this.buckets[keyHash];
const node = bucketLinkedList.find({key});
if (node) {
bucketLinkedList.delete(node.value.value);
}
return null;
}
}