当前位置:首页 > JavaScript

js hasmap实现

2026-03-14 05:30:00JavaScript

实现 HashMap 的基本结构

HashMap 的核心是键值对存储,通过哈希函数将键映射到数组索引。基本结构包含一个数组(桶)和哈希函数。

class HashMap {
  constructor(initialCapacity = 16, loadFactor = 0.75) {
    this.buckets = new Array(initialCapacity).fill(null).map(() => []);
    this.size = 0;
    this.loadFactor = loadFactor;
    this.capacity = initialCapacity;
  }
}

哈希函数设计

哈希函数将键转换为数组索引。常用方法是使用字符编码或多项式滚动哈希。

js hasmap实现

_hash(key) {
  let hash = 0;
  for (let i = 0; i < key.length; i++) {
    hash = (hash * 31 + key.charCodeAt(i)) % this.capacity;
  }
  return hash;
}

处理冲突

冲突通过链地址法(链表或数组)解决。每个桶存储一个键值对列表。

js hasmap实现

_set(key, value) {
  const index = this._hash(key);
  const bucket = this.buckets[index];
  for (let i = 0; i < bucket.length; i++) {
    if (bucket[i].key === key) {
      bucket[i].value = value; // 更新现有键
      return;
    }
  }
  bucket.push({ key, value }); // 新增键值对
  this.size++;
  if (this.size / this.capacity > this.loadFactor) {
    this._resize();
  }
}

动态扩容

当元素数量超过负载因子时,扩容数组并重新哈希所有元素。

_resize() {
  const oldBuckets = this.buckets;
  this.capacity *= 2;
  this.buckets = new Array(this.capacity).fill(null).map(() => []);
  this.size = 0;
  for (const bucket of oldBuckets) {
    for (const entry of bucket) {
      this._set(entry.key, entry.value);
    }
  }
}

完整方法实现

包含 getdeletehas 方法。

get(key) {
  const index = this._hash(key);
  const bucket = this.buckets[index];
  for (const entry of bucket) {
    if (entry.key === key) {
      return entry.value;
    }
  }
  return undefined;
}

delete(key) {
  const index = this._hash(key);
  const bucket = this.buckets[index];
  for (let i = 0; i < bucket.length; i++) {
    if (bucket[i].key === key) {
      bucket.splice(i, 1);
      this.size--;
      return true;
    }
  }
  return false;
}

has(key) {
  return this.get(key) !== undefined;
}

注意事项

  • 哈希函数应尽量减少冲突,均匀分布键。
  • 负载因子过高会导致性能下降,通常设置为 0.75
  • 键的类型需支持哈希计算(如字符串或数字)。

通过上述步骤可实现一个基础的 HashMap,支持动态扩容和冲突处理。

标签: jshasmap
分享给朋友:

相关文章

js实现乘

js实现乘

JavaScript 实现乘法运算 在 JavaScript 中实现乘法运算可以通过多种方式完成,包括基本运算符、函数封装以及高级算法(如大数乘法)。以下是几种常见方法: 使用基本乘法运算符 Jav…

js实现复制到剪贴板

js实现复制到剪贴板

使用document.execCommand方法(传统方式,已废弃但部分浏览器仍支持) 该方法适用于旧版浏览器,但已被标记为废弃。执行前需确保文本已被选中: function copyToClipb…

js实现瀑布流

js实现瀑布流

实现瀑布流布局 瀑布流布局是一种常见的网页布局方式,常用于图片展示、商品列表等场景。以下是使用 JavaScript 实现瀑布流布局的几种方法。 纯 JavaScript 实现 通过计算元素的位置和…

js实现抽奖

js实现抽奖

实现抽奖功能的基本思路 抽奖功能的核心是随机选择奖项并展示结果。可以通过数组存储奖项,利用随机数生成索引,最后通过动画增强用户体验。 准备奖项数据 定义一个数组存储奖项信息,每个奖项可以包含名称、图…

js实现二叉树

js实现二叉树

二叉树的基本概念 二叉树是一种树形数据结构,每个节点最多有两个子节点,分别称为左子节点和右子节点。二叉树的常见操作包括插入、删除、遍历等。 二叉树的节点定义 在JavaScript中,二叉树的节点可…

js实现防洪

js实现防洪

防抖(Debounce)实现 防抖的核心思想是在事件触发后延迟执行回调函数,若在延迟时间内再次触发事件,则重新计时。适用于输入框搜索、窗口调整等场景。 function debounce(f…