-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.ts
53 lines (39 loc) · 1013 Bytes
/
index.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
interface IHashTable {
get(key: string): unknown;
set(key: string, value: unknown): void;
remove(key: string): boolean;
}
class HashTable implements IHashTable {
private table: (Array<unknown> | undefined)[];
public size: number;
constructor(size: number) {
this.table = new Array(size);
this.size = 0;
}
private hash(key: string): number {
let total = 0;
for (let i = 0; i < key.length; i++) {
total += key.charCodeAt(i);
}
return total % this.table.length;
}
public get(key: string): unknown {
const index = this.hash(key);
return this.table[index]?.[1] ?? null;
}
public set(key: string, value: unknown) {
const index = this.hash(key);
this.table[index] = [key, value];
this.size++;
}
public remove(key: string) {
const index = this.hash(key);
if (this.table[index]?.length) {
this.table[index] = undefined;
this.size--;
return true;
}
return false;
}
}
export default HashTable;