Sometimes we need to combine containers together using a join function and get a new container. We'll write a static join method that takes in 2 HashTables and creates a new HashTable with all the values. For the sake of simplicity, we'll let the values from the second one override the values for the first one if there are any keys present in both of them.
Example
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; }
You can test this using −
Example
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();
Example
This will give the output −
0: 1: 2: 3: 4: { 15: 21 } 5: 6: 7: 8: { 30: 1 } 9: { 20: 72 } 10: { 10: 94 } --> { 21: 6 } --> { 32: 34 }