บางครั้งเราต้องรวม container สองตัวด้วย join function และได้ container ใหม่ เราจะเขียน static join method ที่รับ 2 HashTables และสร้าง HashTable ใหม่พร้อมค่าทั้งหมด เพื่อความเรียบง่าย เราจะให้ค่าจากตัวที่สอง override ค่าตัวแรกถ้ามีคีย์ซ้ำกัน
ตัวอย่างโค้ด
static join(table1, table2) {
// ตรวจสอบว่าทั้งสอง args เป็น 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 }