美文网首页antdreact + dva + antd
25 分钟详解使用 JavaScript 实现哈希算法和哈希表

25 分钟详解使用 JavaScript 实现哈希算法和哈希表

作者: 求知久久编程学院 | 来源:发表于2020-02-01 23:36 被阅读0次

查看视频:https://www.qiuzhi99.com/movies/algorithms/962.html

function hashStringToInt(s, tableSize) {
  let hash = 17;

  for (let i = 0; i < s.length; i++) {
    hash = (13 * hash * s.charCodeAt(i)) % tableSize;
  }

  return hash;
}

class HashTable {
  table = new Array(3333);
  numItems = 0;

  resize = () => {
    const newTable = new Array(this.table.length * 2);

    this.table.forEach(item => {
      if (item) {
        const idx = hashStringToInt(item[0], newTable.length);
        newTable[idx] = item;
      }
    });

    this.table = newTable;
  };

  getItem = key => {
    const idx = hashStringToInt(key, this.table.length);

    if (!this.table[idx]) {
      return null;
    }

    return this.table[idx][1];
  };

  setItem = (key, val) => {
    this.numItems++;
    const loadFactor = this.numItems / this.table.length;

    if (loadFactor > 0.8) {
      this.resize();
    }

    const idx = hashStringToInt(key, this.table.length);
    this.table[idx] = [key, val];
  };
}

const myTable = new HashTable();
myTable.setItem("firstName", "bob");
myTable.setItem("f", "bob1");
myTable.setItem("firstNafe", "bob2");
myTable.setItem("firstNafe", "bob3");
console.log(myTable.getItem("firstName"));
console.log(myTable.getItem("f"));
console.log(myTable.getItem("firstNafe"));

相关文章

  • 25 分钟详解使用 JavaScript 实现哈希算法和哈希表

    查看视频:https://www.qiuzhi99.com/movies/algorithms/962.html

  • 「Redis源码解读」—数据结构(二)哈希表

    Redis的字典使用哈希表作为底层实现 知识点 1.数据结构 哈希节点 哈希表 类型处理函数 2.哈希 哈希算法 ...

  • LRU 缓存机制实现:哈希表 + 双向链表

    算法详解 LRU 缓存机制可以通过哈希表辅以双向链表实现,我们用一个哈希表和一个双向链表维护所有在缓存中的键值对。...

  • Redis数据结构与对象——哈希

    1 字典的实现 Redis的字典使用哈希表作为底层实现,一个哈希表可以有多个哈希表节点,即每个哈希表节点就保存了字...

  • 4.字典

    字典 1. 字典的实现 Redis的字典使用哈希表作为底层实现,一个哈希表里面可以有多个哈希表节点,每个哈希表节点...

  • 数据结构和算法

    1.哈希表哈希算法详解(附带 iOS 开发中实际应用) 2.链表iOS 数据结构之链表

  • 使用JavaScript实现哈希表

    关于哈希表的原理详见我的上一篇文章简单易懂数据结构之哈希表 前言 JavaScript中是有哈希类型的数据结构的,...

  • Redis中的字典

    Redis中的字典 Redis中的字典使用哈希表作为底层实现,一个哈希表中可以有多个哈希表结点,而每个哈希表结点保...

  • node的crypto模块

    crypto的目的是提供通用的加密和哈希算法,javascript可以实现,但速度很慢,node使用了c/c++实...

  • Redis 字典(dict.h/dict.c)(4)

    Redis字典的底层实现为哈希表, 每个字典使用两个哈希表, 一般情况下只使用 0 号哈希表, 只有在 rehas...

网友评论

    本文标题:25 分钟详解使用 JavaScript 实现哈希算法和哈希表

    本文链接:https://www.haomeiwen.com/subject/qudfxhtx.html