Slide 1

Slide 1 text

Hash Table

Slide 2

Slide 2 text

What does a hash table do ? A hash table is a data structure that uses hashing to implement mappings of key / value pairs.

Slide 3

Slide 3 text

What does a hash table do ? A simplistic diagram 1. Takes a key / value pair as input 2. Key goes through the hash function and returns an index 3. The pair is stored at that index hash function 1 { key: value }

Slide 4

Slide 4 text

What makes the hash table great ? • A hash function is irreversible. One cannot take the index and find the key. It only works one way. • A hash table is deterministic system. One gets the same result from the same input every time. • A hash table is very efficient. The time complexity in big O notation is O(1).

Slide 5

Slide 5 text

Notes • However it is possible for two different inputs to return the same result. This is called a collision. • Collisions are stored in a nested array. This method is called seperate chaining. • This is also why the time complexity worst case is O(n), n being the number of inputs.

Slide 6

Slide 6 text

Before we get to the code • Hash tables are included in most programming languages. This article is for a better understanding on how they work than a tutorial on how to implement one yourself. • In the following code example, we will implement an simple hash function. There are multiple ways to write them.

Slide 7

Slide 7 text

code review Hash Table

Slide 8

Slide 8 text

First comes the hash function. It takes a key of type string and an integer size as parameter.

Slide 9

Slide 9 text

The hashedkey is the sum of each character's code.

Slide 10

Slide 10 text

The size is the length of the array storing the key/value pairs. Thus hashedkey % size returns the index.

Slide 11

Slide 11 text

Then the hash table as an IIFE to immediately create the instance.

Slide 12

Slide 12 text

Fill the buckets array with Map objects to handle collisions.

Slide 13

Slide 13 text

The insert function invoking the hash function to get the index.

Slide 14

Slide 14 text

Then use the set method from Map object to store the key/value pair.

Slide 15

Slide 15 text

The remove function will save the value of the element to be removed with the get method of the Map object.

Slide 16

Slide 16 text

The delete method of Map will remove the element.

Slide 17

Slide 17 text

The search function returns the value with get method of Map with the appropriate index returned by the hash function.

Slide 18

Slide 18 text

The myBuckets function simply logs the buckets array.

Slide 19

Slide 19 text

All that is left to do is return the closures in an object.

Slide 20

Slide 20 text

Since we referenced hashTable to an Immediatly Invoked Function Expression, we can just invoke our methods.

Slide 21

Slide 21 text

Play around with the code on codepen by clicking the link below