在 Javascript 中连接两个哈希表
web developmentfront end technologyjavascript
有时我们需要使用连接函数将容器组合在一起并获取一个新容器。我们将编写一个静态连接方法,该方法接受 2 个哈希表并创建一个包含所有值的新哈希表。为了简单起见,如果两个哈希表中都存在任何键,我们将让第二个哈希表的值覆盖第一个哈希表的值。
示例
static join(table1, table2) { // 检查两个参数是否都是哈希表 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 }