当前位置:首页 > JavaScript

js实现hashmap

2026-02-01 18:19:09JavaScript

实现基础结构

使用对象或Map类作为基础存储结构。对象方式适合简单键值对,Map类支持更复杂的键类型(如对象、函数)。

js实现hashmap

// 对象实现
const hashMap = {};

// Map类实现
const map = new Map();

处理哈希冲突

采用链表法解决冲突,每个哈希桶存储一个链表。当多个键映射到同一索引时,将新元素添加到链表末尾。

js实现hashmap

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

  _hash(key) {
    let hashCode = 0;
    for (let i = 0; i < key.length; i++) {
      hashCode = (hashCode << 5) - hashCode + key.charCodeAt(i);
    }
    return hashCode % this.buckets.length;
  }
}

实现核心方法

包含set、get、has、delete等基本操作,处理动态扩容逻辑。

set(key, value) {
  const index = this._hash(key);
  const bucket = this.buckets[index];
  const found = bucket.find(item => item.key === key);

  if (found) {
    found.value = value;
  } else {
    bucket.push({ key, value });
    this._resize();
  }
}

get(key) {
  const index = this._hash(key);
  const bucket = this.buckets[index];
  const found = bucket.find(item => item.key === key);
  return found ? found.value : undefined;
}

动态扩容机制

当元素数量超过容量阈值时自动扩容,通常扩大为当前容量的两倍。

_resize() {
  const occupied = this.buckets.filter(b => b.length > 0).length;
  if (occupied / this.buckets.length > this.loadFactor) {
    const oldBuckets = this.buckets;
    this.buckets = new Array(oldBuckets.length * 2).fill(null).map(() => []);
    oldBuckets.forEach(bucket => {
      bucket.forEach(item => {
        const newIndex = this._hash(item.key);
        this.buckets[newIndex].push(item);
      });
    });
  }
}

完整实现示例

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

  _hash(key) {
    let hash = 0;
    const stringKey = String(key);
    for (let i = 0; i < stringKey.length; i++) {
      hash = (hash << 5) - hash + stringKey.charCodeAt(i);
    }
    return Math.abs(hash % this.buckets.length);
  }

  set(key, value) {
    const index = this._hash(key);
    const bucket = this.buckets[index];
    const existing = bucket.find(item => item.key === key);

    if (existing) {
      existing.value = value;
    } else {
      bucket.push({ key, value });
      this.size++;
      if (this.size / this.buckets.length > this.loadFactor) {
        this._resize();
      }
    }
    return this;
  }

  get(key) {
    const index = this._hash(key);
    const bucket = this.buckets[index];
    const found = bucket.find(item => item.key === key);
    return found ? found.value : undefined;
  }

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

  delete(key) {
    const index = this._hash(key);
    const bucket = this.buckets[index];
    const itemIndex = bucket.findIndex(item => item.key === key);

    if (itemIndex >= 0) {
      bucket.splice(itemIndex, 1);
      this.size--;
      return true;
    }
    return false;
  }

  _resize() {
    const newCapacity = this.buckets.length * 2;
    const newBuckets = new Array(newCapacity).fill(null).map(() => []);

    this.buckets.forEach(bucket => {
      bucket.forEach(item => {
        const newIndex = this._hash(item.key);
        newBuckets[newIndex].push(item);
      });
    });

    this.buckets = newBuckets;
  }
}

标签: jshashmap
分享给朋友:

相关文章

js实现vue

js实现vue

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

js实现轮播图

js实现轮播图

基础轮播图实现 使用HTML、CSS和JavaScript实现一个简单的自动轮播图。HTML结构包含一个容器和多个图片项。 <div class="slider"> <div…

js实现图片放大缩小

js实现图片放大缩小

实现图片放大缩小的基础方法 使用CSS的transform: scale()属性可以快速实现图片的放大缩小效果。通过JavaScript动态修改该属性值: const img = document…

js实现pdf在线预览

js实现pdf在线预览

使用PDF.js实现PDF在线预览 PDF.js是由Mozilla开发的一个开源JavaScript库,可以在网页中直接渲染PDF文件。以下是实现PDF在线预览的步骤: 引入PDF.js库 在H…

js实现图表

js实现图表

在JavaScript中实现图表通常使用流行的图表库,以下是几种常见的方法和工具: 使用Chart.js Chart.js是一个简单灵活的库,适合快速生成响应式图表。安装方式包括CDN引入或npm安…

js实现vr

js实现vr

使用WebXR API实现VR体验 WebXR是浏览器中实现VR和AR体验的标准API,它取代了早期的WebVR。现代浏览器如Chrome、Edge和Firefox已支持WebXR。 // 初始化W…