使用 JavaScript 建立雜湊表


讓我們設定一個簡單類,我們將在其中定義所有這些方法。我們將建立一個容器物件來儲存雜湊表,並建立一個顯示函式來顯示錶。請注意,對於衝突解決,我們將使用連結。

顯示函式採用表中的每個條目(雜湊值),並列印與之相關的所有對。

示例

我們還將在原型上建立一個新類以儲存鍵值對。

class HashTable {
   constructor() {
      this.container = [];
      // Populate the container with empty arrays
      // which can be used to add more elements in
      // cases of collisions
      for(let i=0; i < 11; i ++ ) {
         this.container.push([]);
      }
      display() {
         this.container.forEach((value, index) => {
            let chain = value
            .map(({ key, value }) => `{ ${key}: ${value} }`)
            .join(" --> ");
            console.log(`${index}: ${chain}`);
         });
      }
      hash(key) {
         return key % 11;
      }
   }
   HashTable.prototype.KVPair = class {
      constructor(key, value) {
         this.key = key;
         this.value = value;
      }
   }
}

我們在 display 方法中使用了一些高階功能,例如解構。這有助於避免樣板程式碼。

更新於:15-6 月 - 2020

336 瀏覽次數

開啟您的職業生涯

透過完成課程獲得認證

開始
廣告
© . All rights reserved.