在 Javascript 中加入兩個雜湊表


有時我們需要使用 join 函式將容器結合在一起並獲取一個新容器。我們編寫一個靜態 join 方法,它接收 2 個雜湊表,並建立一個包含所有值的新雜湊表。為了簡單起見,如果兩個雜湊表中有一些相同的鍵,那麼我們將允許第二個雜湊表的值覆蓋第一個雜湊表的值。 

示例

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 }

更新於: 15-Jun-2020

443 次瀏覽

開啟你的 職業

透過完成課程獲取認證

立即開始
廣告
© . All rights reserved.