티스토리 뷰

Algorithm

해시 테이블(hash table) JavaScript

Kyeongti 2021. 10. 27. 11:17

 

/* Hash Table */
const HashTable = (function () {
  function HashTable(max) {
    this.max = max;
    this.storage = [];
  }

  function Hash(string, max) {
    let hash = 0;
    for (let i = 0; i < string.length; i++) {
        hash += string[i].charCodeAt();
    }

    this.index = hash % max;
  }

  HashTable.prototype.add = function (key, value) {
    const hash = new Hash(key, this.max);
    const index = hash.index;
    const storage = this.storage;

    if (storage[index] === undefined) {
      storage[index] = [
        [key, value],
      ];
    } else {
        let inserted = false;
        for (let i = 0; i < storage[index].length; i++) {
          if (storage[index][i][0] === key) {
            storage[index][i][1] = value;
            inserted = true;
          }
        }
        if (!inserted) {
          storage[index].push([key, value]);
        }

    }
  };

  HashTable.prototype.remove = function (key) {
    const hash = new Hash(key, this.max);
    const index = hash.index;
    const storage = this.storage;

    if (storage[index].length === 1 && storage[index][0][0] === key) {
      delete storage[index];
    } else {
        for (let i = 0; i < storage[index].length; i++) {
            if (storage[index][i][0] === key) {
                storage[index].splice(i, 1);
            }
        }
    }

  };
    
  HashTable.prototype.print = function () {
    return this.storage;
  }
  return HashTable;
})();


const ht = new HashTable(14); // 크기를 14로 제한함
ht.add('kyeong', 'person');
ht.add('baduggi', 'dog');
ht.add('mandu', 'food');
ht.add('soccer', 'exercise');
ht.print();
댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
TAG
more
«   2024/11   »
1 2
3 4 5 6 7 8 9
10 11 12 13 14 15 16
17 18 19 20 21 22 23
24 25 26 27 28 29 30
글 보관함