This is the third post in my series Data Structures and Algorithms using JavaScript. Last week, I discussed The Array Data Structure. This week I am going to talk about another popular data structure, the Hash Table. Much like in my previous post, I will cover the Big O of common Hash Table
actions (insert
, lookup
, delete
, search
). We will also create our own Hash Table data structure! Let’s get to it.
A defintion of a hash Table
A definition of Insert
A definition of Lookup
A definition of Delete
A definition of Search
A definition of Hash Collision
class HashTable {
constructor(size){
this.data = new Array(size);
}
_hash(key) {
let hash = 0;
for (let i =0; i < key.length; i++){
hash = (hash + key.charCodeAt(i) * i) % this.data.length
}
return hash;
}
get(key) {
let address = this._hash(key);
const currentBucket = this.data[address];
if (currentBucket) {
for(let i = 0; i < currentBucket.length; i++) {
if (currentBucket[i][0] === key) {
return currentBucket[i][1]
}
}
}
// O(n)
return undefined
}
set(key, value) {
let address = this._hash(key)
if (!this.data[address]) {
this.data[address] = [];
}
this.data[address].push([key, value]);
// O(1)
return this.data
}
}
const myHashTable = new HashTable(50);
myHashTable.set('grapes', 10000)
// myHashTable.get('grapes')
// myHashTable.set('apples', 9)
// myHashTable.get('apples')