JavaScript Data Structures: Hash Table: Get keys

Intro 🌐

Last time, we learned how to get data from our hash table .

Today, we'll learn how to get the keys of our Hash Table.


Requirements 💭

We need the following parts to get the keys from our Hash Table:

  • a method to get the keys (keys)

Starter Code ▶️

We start with the code with the set method, so that we can use the set method to add some data.

class Hashtable {
  constructor() {
    this.data = [];
    this.size = 0;
  }

  hash(key) {
    const chars = key.split("");
    const charCodes = chars.map((char) => char.charCodeAt());
    const charCodeSum = charCodes.reduce((acc, cur) => acc + cur);
    return charCodeSum;
  }

  set(key, value) {
    const hash = this.hash(key);

    if (!this.data[hash]) {
      this.data[hash] = [];
    }

    this.data[hash].push([key, value]);

    this.size++;
  }
}

If you are not familiar with the hash function, re-read this post.


Thoughts 💭

First, we should think about the constraints and possibilities:

  • first, we declare an empty array for the keys
  • then we iterate over the data array
  • if there is data (= array of key-value pairs) at this specific index, iterate over this data (= the single key-value pairs)
  • add the data (= key) to the keys array
  • return the keys array

Example

We want to get all the keys.

// current hash table data:
[
  [["age", 33]],
  [
    ["name", "miku86"],
    ["mean", false],
  ],
];

// desired data:
["age", "name", "mean"];

Steps

// current hash table data:
[
  [["age", 33]],
  [
    ["name", "miku86"],
    ["mean", false],
  ],
];

// then we iterate over the data array
[["age", 33]];

// if there is data (= array of key-value pairs) at this specific index
// then iterate over this data (= the single key-value pairs)
["age", 33];

// add the data (= key) to the keys array
["age"];

// then we iterate over the data array
[
  ["name", "miku86"],
  ["mean", false],
];

// if there is data (= array of key-value pairs) at this specific index
// then iterate over this data (= the single key-value pairs)
["name", "miku86"];

// add the data (= key) to the keys array
["age", "name"];

// if there is data (= array of key-value pairs) at this specific index
// then iterate over this data (= the single key-value pairs)
["mean", false];

// add the data (= key) to the keys array
["age", "name", "mean"];

// desired data:
["age", "name", "mean"];


Implementation ⛑

// a Hash Table class
class Hashtable {
  constructor() {
    this.data = [];
    this.size = 0;
  }

  hash(key) {
    const chars = key.split("");
    const charCodes = chars.map((char) => char.charCodeAt());
    const charCodeSum = charCodes.reduce((acc, cur) => acc + cur);
    return charCodeSum;
  }

  set(key, value) {
    const hash = this.hash(key);

    if (!this.data[hash]) {
      this.data[hash] = [];
    }

    this.data[hash].push([key, value]);

    this.size++;
  }

  keys() {
    // declare an empty array for the keys
    const keys = [];

    // iterate over the data array (I call a single array a "bucket")
    for (let bucket of this.data) {
      // if there is data (= array of key-value pairs) at this specific index
      if (bucket) {
        // iterate over this data (= the single key-value pairs)
        for (let item of bucket) {
          // add the data (= key) to the keys array
          keys.push(item[0]);
        }
      }
    }

    // return the keys array
    return keys;
  }
}

Note: I'm using a for ... of-loop. If you don't know how this works, you can read about it on MDN. You can use whatever you want to use, a default for-loop, a for ... in-loop, a functional approach etc.


Result

// create a new hash table
const newHashtable = new Hashtable();

// add three new key-value pairs
newHashtable.set("name", "miku86");
newHashtable.set("mean", false);
newHashtable.set("age", 33);

// show the hash table data
console.log(newHashtable.data);
// [ <301 empty items>, [ [ 'age', 33 ] ], <115 empty items>, [ [ 'name', 'miku86' ], [ 'mean', false ] ] ]

// show the keys
console.log(newHashtable.keys());
// [ 'age', 'name', 'mean' ] ✅


Next Part ➡️

We managed to write a function to get all keys, great work!

Next time, we'll learn how to get all values from our Hash Table.

Need some mentoring? Click here!


Further Reading 📖


Questions ❔

  • How would you implement the keys-function?
  • How would you write this code in a functional style?