DEV Community

miku86
miku86

Posted on

JavaScript Data Structures: Hash Table: Setup

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 } } 
Enter fullscreen mode Exit fullscreen mode

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 } โœ… 
Enter fullscreen mode Exit fullscreen mode

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?

Top comments (0)