यहां HashTable क्लास का पूरा कार्यान्वयन है। इसे निश्चित रूप से अधिक कुशल डेटा संरचनाओं और कोलिजन रिज़ॉल्यूशन एल्गोरिदम का उपयोग करके सुधारा जा सकता है।
उदाहरण
class HashTable {
constructor() {
this.container = [];
// कंटेनर को खाली ऐरे से भरें
// जिनका उपयोग कोलिजन के मामले में अधिक एलिमेंट्स जोड़ने के लिए किया जा सकता है
for (let i = 0; i < 11; i++) {
this.container.push([]);
}
}
display() {
this.container.forEach((value, index) => {
let chain = value
.map(({ key, value }) => `{ ${key}: ${value} }`)
.join(" --> ");
console.log(`${index}: ${chain}`);
});
}
put(key, value) {
let hashCode = this.hash(key);
for (let i = 0; i < this.container[hashCode].length; i++) {
// दिए गए की के साथ मौजूदा वैल्यू को बदलें
// अगर यह पहले से मौजूद है
if (this.container[hashCode][i].key === key) {
this.container[hashCode][i].value = value;
return;
}
}
// जोड़ी को ऐरे के अंत में पुश करें
this.container[hashCode].push(new this.KVPair(key, value));
}
get(key) {
let hashCode = this.hash(key);
for (let i = 0; i < this.container[hashCode].length; i++) {
// चेन में एलिमेंट ढूंढें
if (this.container[hashCode][i].key === key) {
return this.container[hashCode][i];
}
}
return undefined;
}
remove(key) {
let hashCode = this.hash(key);
for (let i = 0; i < this.container[hashCode].length; i++) {
// चेन में एलिमेंट ढूंढें
if (this.container[hashCode][i].key === key) {
this.container[hashCode].splice(i, 1);
return true;
}
}
return false;
}
hash(key) {
return key % 11;
}
forEach(callback) {
// प्रत्येक चेन के लिए
this.container.forEach(elem => {
// प्रत्येक चेन में प्रत्येक एलिमेंट के लिए KV जोड़ी पर कॉलबैक कॉल करें
elem.forEach(({ key, value }) => callback(key, value));
});
}
static join(table1, table2) {
// जांचें कि दोनों आर्ग्यूमेंट्स HashTables हैं
if (!table1 instanceof HashTable || !table2 instanceof HashTable) {
throw new Error("अवैध आर्ग्यूमेंट्स");
}
let combo = new HashTable();
table1.forEach((k, v) => combo.put(k, v));
table2.forEach((k, v) => combo.put(k, v));
return combo;
}
}
HashTable.prototype.KVPair = class {
constructor(key, value) {
this.key = key;
this.value = value;
}
};