-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathhash_map.js
121 lines (104 loc) · 2.49 KB
/
hash_map.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
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
const INITIAL_CAPACITY = 10;
const LOAD_FACTOR = 0.75;
class Entry {
constructor(key, value) {
this.key = key;
this.value = value;
this.next = null;
}
}
class HashMap {
constructor() {
this.size = 0;
this.capacity = INITIAL_CAPACITY;
this.table = new Array(this.capacity).fill(null);
}
hash(key) {
let hashValue = 0;
for (let i = 0; i < key.length; i++) {
hashValue = (hashValue * 31) + key.charCodeAt(i);
}
return hashValue % this.capacity;
}
resize() {
// JS动态数组本身无需调整容量,此处仅为演示
const newCapacity = this.capacity * 2;
const newTable = new Array(newCapacity).fill(null);
for (let i = 0; i < this.capacity; i++) {
let entry = this.table[i];
while (entry) {
const newIndex = this.hash(entry.key);
const newEntry = new Entry(entry.key, entry.value);
newEntry.next = newTable[newIndex];
newTable[newIndex] = newEntry;
entry = entry.next;
}
}
this.table = newTable;
this.capacity = newCapacity;
}
put(key, value) {
if ((this.size / this.capacity) > LOAD_FACTOR) {
this.resize();
}
const index = this.hash(key);
let entry = this.table[index];
while (entry) {
if (entry.key === key) {
entry.value = value;
return;
}
entry = entry.next;
}
const newEntry = new Entry(key, value);
newEntry.next = this.table[index];
this.table[index] = newEntry;
this.size++;
}
get(key) {
const index = this.hash(key);
let entry = this.table[index];
while (entry) {
if (entry.key === key) {
return entry.value;
}
entry = entry.next;
}
return -1;
}
delete(key) {
const index = this.hash(key);
let entry = this.table[index];
let prev = null;
while (entry) {
if (entry.key === key) {
if (prev) {
prev.next = entry.next;
} else {
this.table[index] = entry.next;
}
this.size--;
return;
}
prev = entry;
entry = entry.next;
}
}
}
// 测试
const map = new HashMap();
map.put('apple', 10);
map.put('banana', 20);
map.put('orange', 30);
console.log("apple:", map.get('apple'));
console.log("banana:", map.get('banana'));
console.log("grape:", map.get('grape'));
map.delete('banana');
console.log("banana after delete:", map.get('banana'));
/*
jarry@MacBook-Pro hash % node hash_map.js
apple: 10
banana: 20
grape: -1
banana after delete: -1
*/