Skip to content

Commit 650872c

Browse files
committed
Add the JavaScript code to docs (Chapter of Hashing)
1 parent 630bbac commit 650872c

File tree

1 file changed

+71
-1
lines changed

1 file changed

+71
-1
lines changed

docs/chapter_hashing/hash_map.md

+71-1
Original file line numberDiff line numberDiff line change
@@ -132,7 +132,23 @@ comments: true
132132
=== "JavaScript"
133133

134134
```js title="hash_map.js"
135+
/* 初始化哈希表 */
136+
const map = new ArrayHashMap();
137+
/* 添加操作 */
138+
// 在哈希表中添加键值对 (key, value)
139+
map.set(12836, '小哈');
140+
map.set(15937, '小啰');
141+
map.set(16750, '小算');
142+
map.set(13276, '小法');
143+
map.set(10583, '小鸭');
144+
145+
/* 查询操作 */
146+
// 向哈希表输入键 key ,得到值 value
147+
let name = map.get(15937);
135148

149+
/* 删除操作 */
150+
// 在哈希表中删除键值对 (key, value)
151+
map.delete(10583);
136152
```
137153

138154
=== "TypeScript"
@@ -244,7 +260,20 @@ comments: true
244260
=== "JavaScript"
245261

246262
```js title="hash_map.js"
247-
263+
/* 遍历哈希表 */
264+
// 遍历键值对 key->value
265+
for (const entry of map.entries()) {
266+
if (!entry) continue;
267+
console.info(entry.key + ' -> ' + entry.val);
268+
}
269+
// 单独遍历键 key
270+
for (const key of map.keys()) {
271+
console.info(key);
272+
}
273+
// 单独遍历值 value
274+
for (const val of map.values()) {
275+
console.info(val);
276+
}
248277
```
249278

250279
=== "TypeScript"
@@ -500,7 +529,48 @@ $$
500529
=== "JavaScript"
501530

502531
```js title="array_hash_map.js"
532+
/* 键值对 Number -> String */
533+
class Entry {
534+
constructor(key, val) {
535+
this.key = key;
536+
this.val = val;
537+
}
538+
}
539+
540+
/* 基于数组简易实现的哈希表 */
541+
class ArrayHashMap {
542+
#bucket
543+
constructor() {
544+
// 初始化一个长度为 100 的桶(数组)
545+
this.#bucket = new Array(100).fill(null);
546+
}
503547

548+
/* 哈希函数 */
549+
#hashFunc(key) {
550+
return key % 100;
551+
}
552+
553+
/* 查询操作 */
554+
get(key) {
555+
let index = this.#hashFunc(key);
556+
let entry = this.#bucket[index];
557+
if (entry === null) return null;
558+
return entry.val;
559+
}
560+
561+
/* 添加操作 */
562+
set(key, val) {
563+
let index = this.#hashFunc(key);
564+
this.#bucket[index] = new Entry(key, val);
565+
}
566+
567+
/* 删除操作 */
568+
delete(key) {
569+
let index = this.#hashFunc(key);
570+
// 置为 null ,代表删除
571+
this.#bucket[index] = null;
572+
}
573+
}
504574
```
505575

506576
=== "TypeScript"

0 commit comments

Comments
 (0)