当前位置:首页 > 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;
  }
}

哈希函数设计

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

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

处理冲突

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

_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 方法。

js hasmap实现

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实现vue

js实现vue

Vue.js 简介 Vue.js 是一个渐进式 JavaScript 框架,用于构建用户界面。其核心库专注于视图层,易于与其他库或现有项目整合。 实现 Vue.js 的基本步骤 安装 Vue.j…

vue实现js休眠

vue实现js休眠

实现 JavaScript 休眠的方法 在 Vue 中实现 JavaScript 休眠(延迟执行)可以通过以下方式实现。由于 JavaScript 本身没有内置的 sleep 函数,通常使用 Prom…

节流js实现

节流js实现

节流(Throttle)的实现原理 节流是一种限制函数执行频率的技术,确保函数在一定时间间隔内最多执行一次。适用于高频触发事件(如滚动、输入、窗口调整等)的场景。 基础实现方式 使用时间戳判断是否执…

js实现图片

js实现图片

图片加载与显示 在JavaScript中,可以通过Image对象动态加载图片。创建实例后设置src属性触发加载,通过onload回调处理加载完成后的操作: const img = new Ima…

js实现滚动

js实现滚动

实现滚动效果的方法 在JavaScript中实现滚动效果可以通过多种方式完成,以下是一些常见的方法: 使用window.scrollTo() window.scrollTo()方法可以将页面滚动到指…

js实现上传文件

js实现上传文件

文件上传的基本实现 使用HTML的<input type="file">元素配合JavaScript的File API可以实现文件上传功能。 <input type="file"…