เมื่อเพิ่มองค์ประกอบลงในตารางแฮช ส่วนที่สำคัญที่สุดคือการแก้ปัญหาการชน เราจะใช้การโยงสิ่งเดียวกัน มีอัลกอริทึมอื่นๆ ที่คุณสามารถอ่านได้ที่นี่:https://en.wikipedia.org/wiki/Hash_table#Collision_ resolution
ทีนี้มาดูการใช้งานกัน เราจะสร้างฟังก์ชันแฮชที่จะทำงานกับจำนวนเต็มเท่านั้นเพื่อให้ง่าย แต่อัลกอริธึมที่ซับซ้อนกว่านี้สามารถใช้แฮชทุกอ็อบเจกต์ได้ -
ตัวอย่าง
put(key, value) {
let hashCode = hash(key);
for(let i = 0; i < this.container[hashCode].length; i ++) {
// Replace the existing value with the given key
// if it already exists
if(this.container[hashCode][i].key === key) {
this.container[hashCode][i].value = value; return;
}
}
// Push the pair at the end of the array
this.container[hashCode].push(new this.KVPair(key, value));
} คุณสามารถทดสอบได้โดยใช้
ตัวอย่าง
let ht = new HashTable(); ht.put(10, 94); ht.put(20, 72); ht.put(30, 1); ht.put(21, 6); ht.put(15, 21); ht.put(32, 34); ht.display();
ผลลัพธ์
สิ่งนี้จะให้ผลลัพธ์ -
0:
1:
2:
3:
4: { 15: 21 }
5:
6:
7:
8: { 30: 1 }
9: { 20: 72 }
10: { 10: 94 } -->{ 21: 6 } -->{ 32: 34 }