美文网首页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.haomeiwen.com/subject/qudfxhtx.html