JS实现一个简单版HashMap

349 阅读1分钟
1. HashMap原理
  • HashMap中,采用数组+链表的方式来实现对数据的储存(因为数组是查找快,增删满;链表是查找慢,增删快)
  • 简单的用图形表示一下HashMap实现原理

HashMap.png

2. 使用JS实现一个简单的HashMap(这里用取余代替Hash算法)
2.1 规定HashMap存储长度为8,并定义MyHashMap函数
const mapSize = 8;
function MyHashMap() {
  this.initStore();
}
2.2 定义初始化链表的函数
MyHashMap.prototype.initStore = function () {
  this.store = new Array(mapSize)
  for (let i = 0; i < mapSize; i++) {
    this.store[i] = { // 初始链表头
      next: null
    };
  }
}
2.3 定义自己的Hash算法
MyHashMap.prototype.hash = function (n) {
  return n % mapSize; // 取余8
}
2.4 定义获取HashMap元素值的方法
MyHashMap.prototype.get = function (key) {
  // 根据key计算房间号
  let index = this.hash(key);
  let queue = this.store[index];

  // 看当前的逻辑
  while (queue) {
    if (queue.key === key) {
      return queue.val;
    } else {
      // 指针下移
      queue = queue.next;
    }
  }
  return undefined;
}
2.5 定义判断HashMap是否已经存在某元素的函数
MyHashMap.prototype.has = function (key) {
  return !!this.get(key)
}
2.6 定义存储数据的函数
MyHashMap.prototype.set = function (key, val) {
  // 根据key计算房间号
  let index = this.hash(key);
  let queue = this.store[index];
  // 找后面next是否有数据,对比key,如果满足就覆盖
  while (queue.next) {
    if (queue.next.key === key) {
      // 覆盖
      queue.next.val = val;
      return;
    } else {
      // 再看下一个   // 指针下移
      queue = queue.next;
    }
  }
  // 假设第一次调用,直接链上去
  queue.next = {
    next: null,
    // key:key,
    key,
    val
  }
}