티스토리 뷰
/* 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();
'Algorithm' 카테고리의 다른 글
LeetCode - Minimum Absolute Difference in BST in JavaScript (0) | 2021.11.25 |
---|---|
LeetCode - Lowest Common Ancestor of a Binary Search Tree in JavaScript (0) | 2021.11.24 |
Merge Sort in JavaScript (0) | 2021.11.20 |
자료구조 Queue(큐) in JavaScript (0) | 2021.11.07 |
자료구조 Stack in JavaScript (0) | 2021.11.07 |
댓글