-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathHashTable.ts
More file actions
48 lines (43 loc) · 1.33 KB
/
HashTable.ts
File metadata and controls
48 lines (43 loc) · 1.33 KB
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
export class HashTable<T> {
private dataMap: Array<any>
constructor(size: number = 7) {
this.dataMap = new Array<any>(size);
}
public set(key: string, value: T): HashTable<T> {
let index = this.hash(key);
if (!this.dataMap[index]) {
this.dataMap[index] = [];
}
this.dataMap[index].push([key, value]);
return this;
}
public get(key: string): T | undefined {
let index = this.hash(key);
if (this.dataMap[index]) {
for (let i: number = 0; i < this.dataMap[index].length; i++) {
if (this.dataMap[index][i][0] === key) {
return this.dataMap[index][i][1];
}
}
}
return undefined;
}
public keys(): Array<string> {
let keys:Array<string> = [];
for (let i: number = 0; i < this.dataMap.length; i++) {
if (this.dataMap[i]) {
for (let j: number = 0; j < this.dataMap[i].length; j++) {
keys.push(this.dataMap[i][j][0]);
}
}
}
return keys;
}
private hash(key: string) {
let hash = 0;
for (let i: number = 0; i < key.length; i++) {
hash = (hash + key.charCodeAt(i) * 23) % this.dataMap.length;
}
return hash;
}
}