บางครั้ง เราจำเป็นต้องรวมคอนเทนเนอร์เข้าด้วยกันโดยใช้ฟังก์ชัน join และรับคอนเทนเนอร์ใหม่ เราจะเขียนวิธีการเข้าร่วมแบบคงที่ซึ่งรับ 2 HashTables และสร้าง HashTable ใหม่พร้อมค่าทั้งหมด เพื่อความง่าย เราจะให้ค่าจากค่าที่สองแทนที่ค่าของค่าแรกหากมีคีย์ใดๆ อยู่ในทั้งสองค่า
ตัวอย่าง
static join(table1, table2) {
// Check if both args are HashTables
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;
} คุณสามารถทดสอบสิ่งนี้ได้โดยใช้ -
ตัวอย่าง
let ht1 = new HashTable(); ht1.put(10, 94); ht1.put(20, 72); ht1.put(30, 1); let ht2 = new HashTable(); ht2.put(21, 6); ht2.put(15, 21); ht2.put(32, 34); let htCombo = HashTable.join(ht1, ht2) htCombo.display();
ตัวอย่าง
สิ่งนี้จะให้ผลลัพธ์ -
0:
1:
2:
3:
4: { 15: 21 }
5:
6:
7:
8: { 30: 1 }
9: { 20: 72 }
10: { 10: 94 } --> { 21: 6 } --> { 32: 34 }