본문 바로가기
프론트엔드

자바스크립트로 구현한 hash table

by 느바 2022. 3. 11.
반응형

자바스크립트로 구현한 hash table

hash table

키를 값에 매핑할 수 있는 구조인, 연관 배열 추가에 사용되는 자료 구조이다.
해시 테이블은 해시 함수를 사용하여 색인(index)을 버킷(bucket)이나 슬롯(slot)의 배열로 계산한다.

출처 : https://ko.wikipedia.org/wiki/%ED%95%B4%EC%8B%9C_%ED%85%8C%EC%9D%B4%EB%B8%94

 

해시 테이블 - 위키백과, 우리 모두의 백과사전

 

ko.wikipedia.org

class HashTable{
    constructor(table_length){
        this.table = new Array(table_length);
        this.size = 0;
    }
    _hash(key){
        let hash = 0;
        for(let i = 0; i<key.length; i++){
            hash += key.charCodeAt(i);
        }
        return hash % this.table.length;
    }
    set(key, value){
        const index = this._hash(key);
        this.table[index] = [key,value];
        this.size++;
    }
    get(key){
        const index = this._hash(key);
        return this.table[index];
    }
    remove(key){
        const index = this._hash(key);
        if(this.table[index] && this.table[index].length){
            this.table[index] = undefined;
            this.size--;
            return true;
        }else{
            return false;
        }
    }
}
const ht = new HashTable(100);
ht.set('steak',10000);
ht.set('milk',500);

 

반응형

'프론트엔드' 카테고리의 다른 글

자바스크립트로 구현한 Tree, BFS, DFS  (0) 2022.03.12
자바스크립트로 구현한 Max Heap  (0) 2022.03.12
단일연결리스트로 구현한 Stack, Queue  (0) 2022.03.10
user story  (0) 2022.03.02
flex-basis  (0) 2022.02.07