Update array_hash_map

This commit is contained in:
krahets
2023-03-15 03:11:43 +08:00
parent 669388128f
commit d5afd93571
10 changed files with 98 additions and 98 deletions

View File

@ -14,10 +14,10 @@ class Entry {
/* 基于数组简易实现的哈希表 */
class ArrayHashMap {
#bucket;
#buckets;
constructor() {
// 初始化一个长度为 100 的桶(数组)
this.#bucket = new Array(100).fill(null);
this.#buckets = new Array(100).fill(null);
}
/* 哈希函数 */
@ -28,7 +28,7 @@ class ArrayHashMap {
/* 查询操作 */
get(key) {
let index = this.#hashFunc(key);
let entry = this.#bucket[index];
let entry = this.#buckets[index];
if (entry === null) return null;
return entry.val;
}
@ -36,22 +36,22 @@ class ArrayHashMap {
/* 添加操作 */
set(key, val) {
let index = this.#hashFunc(key);
this.#bucket[index] = new Entry(key, val);
this.#buckets[index] = new Entry(key, val);
}
/* 删除操作 */
delete(key) {
let index = this.#hashFunc(key);
// 置为 null ,代表删除
this.#bucket[index] = null;
this.#buckets[index] = null;
}
/* 获取所有键值对 */
entries() {
let arr = [];
for (let i = 0; i < this.#bucket.length; i++) {
if (this.#bucket[i]) {
arr.push(this.#bucket[i]);
for (let i = 0; i < this.#buckets.length; i++) {
if (this.#buckets[i]) {
arr.push(this.#buckets[i]);
}
}
return arr;
@ -60,9 +60,9 @@ class ArrayHashMap {
/* 获取所有键 */
keys() {
let arr = [];
for (let i = 0; i < this.#bucket.length; i++) {
if (this.#bucket[i]) {
arr.push(this.#bucket[i]?.key);
for (let i = 0; i < this.#buckets.length; i++) {
if (this.#buckets[i]) {
arr.push(this.#buckets[i]?.key);
}
}
return arr;
@ -71,9 +71,9 @@ class ArrayHashMap {
/* 获取所有值 */
values() {
let arr = [];
for (let i = 0; i < this.#bucket.length; i++) {
if (this.#bucket[i]) {
arr.push(this.#bucket[i]?.val);
for (let i = 0; i < this.#buckets.length; i++) {
if (this.#buckets[i]) {
arr.push(this.#buckets[i]?.val);
}
}
return arr;