mirror of
https://github.com/krahets/hello-algo.git
synced 2024-12-25 10:56:30 +08:00
Add the JavaScript code to docs (Chapter of Hashing)
This commit is contained in:
parent
630bbac285
commit
650872cb05
1 changed files with 71 additions and 1 deletions
|
@ -132,7 +132,23 @@ comments: true
|
|||
=== "JavaScript"
|
||||
|
||||
```js title="hash_map.js"
|
||||
/* 初始化哈希表 */
|
||||
const map = new ArrayHashMap();
|
||||
/* 添加操作 */
|
||||
// 在哈希表中添加键值对 (key, value)
|
||||
map.set(12836, '小哈');
|
||||
map.set(15937, '小啰');
|
||||
map.set(16750, '小算');
|
||||
map.set(13276, '小法');
|
||||
map.set(10583, '小鸭');
|
||||
|
||||
/* 查询操作 */
|
||||
// 向哈希表输入键 key ,得到值 value
|
||||
let name = map.get(15937);
|
||||
|
||||
/* 删除操作 */
|
||||
// 在哈希表中删除键值对 (key, value)
|
||||
map.delete(10583);
|
||||
```
|
||||
|
||||
=== "TypeScript"
|
||||
|
@ -244,7 +260,20 @@ comments: true
|
|||
=== "JavaScript"
|
||||
|
||||
```js title="hash_map.js"
|
||||
|
||||
/* 遍历哈希表 */
|
||||
// 遍历键值对 key->value
|
||||
for (const entry of map.entries()) {
|
||||
if (!entry) continue;
|
||||
console.info(entry.key + ' -> ' + entry.val);
|
||||
}
|
||||
// 单独遍历键 key
|
||||
for (const key of map.keys()) {
|
||||
console.info(key);
|
||||
}
|
||||
// 单独遍历值 value
|
||||
for (const val of map.values()) {
|
||||
console.info(val);
|
||||
}
|
||||
```
|
||||
|
||||
=== "TypeScript"
|
||||
|
@ -500,7 +529,48 @@ $$
|
|||
=== "JavaScript"
|
||||
|
||||
```js title="array_hash_map.js"
|
||||
/* 键值对 Number -> String */
|
||||
class Entry {
|
||||
constructor(key, val) {
|
||||
this.key = key;
|
||||
this.val = val;
|
||||
}
|
||||
}
|
||||
|
||||
/* 基于数组简易实现的哈希表 */
|
||||
class ArrayHashMap {
|
||||
#bucket
|
||||
constructor() {
|
||||
// 初始化一个长度为 100 的桶(数组)
|
||||
this.#bucket = new Array(100).fill(null);
|
||||
}
|
||||
|
||||
/* 哈希函数 */
|
||||
#hashFunc(key) {
|
||||
return key % 100;
|
||||
}
|
||||
|
||||
/* 查询操作 */
|
||||
get(key) {
|
||||
let index = this.#hashFunc(key);
|
||||
let entry = this.#bucket[index];
|
||||
if (entry === null) return null;
|
||||
return entry.val;
|
||||
}
|
||||
|
||||
/* 添加操作 */
|
||||
set(key, val) {
|
||||
let index = this.#hashFunc(key);
|
||||
this.#bucket[index] = new Entry(key, val);
|
||||
}
|
||||
|
||||
/* 删除操作 */
|
||||
delete(key) {
|
||||
let index = this.#hashFunc(key);
|
||||
// 置为 null ,代表删除
|
||||
this.#bucket[index] = null;
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
=== "TypeScript"
|
||||
|
|
Loading…
Reference in a new issue