Loop through a hash table using Javascript

Front End TechnologyWeb DevelopmentJavascript

Now let us create a forEach function that'll allow us to loop over all key-value pairs and call a callback on those values. For this, we just need to loop over each chain in the container and call the callback on the key and value pairs.

Example

forEach(callback) {
   // For each chain
   this.container.forEach(elem => {
      // For each element in each chain call callback on KV pair
      elem.forEach(({ key, value }) => callback(key, value));
   });
}

You can test this using.

Example

let ht = new HashTable();
ht.put(10, 94); ht.put(20, 72);
ht.put(30, 1); ht.put(21, 6);
ht.put(15, 21);
ht.put(32, 34);

let sum = 0;

// Add all the values together
ht.forEach((k, v) => sum += v)

console.log(sum);

Output

This will give the output.

228
raja
Published on 28-Jun-2018 10:26:13
Advertisements