← Blog

JavaScript Data Structures: Hash Table: Setup

February, 2020

Intro 🌐

Last time, we learned how to handle hash collisions.

Today, we’ll use all of the stuff we learned so far to setup our Hash Table.


Requirements πŸ’­

We need the following parts to setup our Hash Table:

  • a Hash Table class
  • a container for our data
  • the size of the data
  • a hash function that inputs a key and outputs an array index

Implementation β›‘

// a Hash Table class
class Hashtable {
  constructor() {
    // a container for our data
    this.data = []

    // the size of the data
    this.size = 0
  }

  // a hash function that inputs a key and outputs an array index
  hash(key) {
    const chars = key.split('')
    const charCodes = chars.map(char => char.charCodeAt())
    const charCodeSum = charCodes.reduce((acc, cur) => acc + cur)
    return charCodeSum
  }
}

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


Result

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

// hash table should have no data and size 0
console.log(newHashtable)
// Hashtable { data: [], size: 0 } βœ…

Next Part ➑️

We’ll learn how to add data to our Hash Table.

Need some mentoring? Click here!


Further Reading πŸ“–


Questions ❔

  • How would you implement the Hash Table?
  • How would you build the hash function? Why?

miku86

Hi! I'm Michael πŸ‘‹ I'm a problem solver and mentor. My goal is to build great products and help you to become a better developer.