এখানে 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 => {
// প্রতিটি চেইনের প্রতিটি উপাদানের জন্য কি-ভ্যালু পেয়ারে কলব্যাক কল করুন
elem.forEach(({ key, value }) => callback(key, value));
});
}
static join(table1, table2) {
// চেক করুন দুটি আর্গুমেন্ট HashTable কিনা
if (!table1 instanceof HashTable || !table2 instanceof HashTable) {
throw new Error("Illegal Arguments");
}
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;
}
};