데이터 관리 유지 구조
리소스 < 속도
데이터를 해시함수 를 거쳐서 인덱스와 값으로 나누게 하는 자료구조이다.
해시테이블의 첫번째는 인덱스, 키 (버킷), 두번째는 해시 값, 벨류(엔트리) 라고 한다.
메뉴로 구분을 해보자면 arrray는 아래와 같고,
menu = [{name : "coffee", price: 1},{name : "juice", price: 2},{name : "milk", price: 3}]
hash table은 이런 형태일 것이다.
menu = { "coffee": 1,"juice": 2,"milk": 3}
const collection = new Map();
collection.set("Nathan", "555-0182");
collection.set("Jane", "555-0182");
console.log(collection.get("Nathan")); // 555-0182
console.log(collection.size); // 2
set()
get()
을 통해 데이터를 업데이트하고 가져올수있다.collection["size"] = false;
console.log(collection.get("size")); // undefined
class HashTable {
constructor() {
this.table = new Array(127);
this.size = 0;
}
}
_hash(key) {
let hash = 0;
for (let i = 0; i < key.length; i++) {
hash += key.charCodeAt(i);
}
return hash;
}
*127 을 넘지 않기 위해서는 아래와 같은 모듈러 operator 추가해준다.
_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 target = this._hash(key);
return this.table[target];
}
remove(key) {
const index = this._hash(key);
if (this.table[index] && this.table[index].length) {
this.table[index] = [];
this.size--;
return true;
} else {
return false;
}
}
}
reference
https://www.youtube.com/watch?v=OFo6Q4AYjis&ab_channel=Hays%7CCoding%26Tech
https://www.freecodecamp.org/news/javascript-hash-table-associative-array-hashing-in-js/