-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhash-table.js
94 lines (69 loc) · 1.65 KB
/
hash-table.js
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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
import LinkedList from './linked-list';
class HashTable {
constructor() {
this.table = [];
}
put(key, value) {
const position = this._djb2HashCode(key);
if (table[position] === undefined) {
table[position] = new LinkedList();
}
this.talbe[position].append(new ValuePair(key, value));
}
remove(key) {
const position = this._djb2HashCode(key);
if (this.table[position] === undefined) {
return false;
}
let current = this.table[position].getHead();
while (current) {
if (current.value.key === key) {
this.table[position].remove(current.vallue);
if (this.table[position].isEmpty()) {
this.table[position] = undefined;
}
return true;
}
current = current.next;
}
return false;
}
get(key) {
const position = this._djb2HashCode(key);
if (this.table[position] === undefined) {
return undefined;
}
let current = this.table[position].getHead();
while (current) {
if (current.value.key === key) {
return current.value.value;
}
current = current.next;
}
return undefined;
}
_loseloseHashCode(key) {
let hash = 0;
for (let i = 0; i < key.length; i++) {
hash += key.charCodeAt(i);
}
return hash % 37;
}
_djb2HashCode(key) {
let hash = 5381;
for (let i = 0; i < key.length; i++) {
hash = hash * 33 + key.charCodeAt(i);
}
return hash % 1013;
}
}
class ValuePair {
constructor(key, value) {
this.key = key;
this.value = value;
}
toString() {
return `[${this.key} - ${this.value}]`;
}
}
export default HashTable;