Last active
May 13, 2023 18:52
-
-
Save adames/bb731f2062ced67b1c3d26356468b237 to your computer and use it in GitHub Desktop.
simple hash table
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Implement hash table | |
let hash = (string, max) => { | |
let hash = 0; | |
for (let i = 0; i< string.length; i++) { | |
hash += string.charCodeAt(i); | |
} | |
return hash % max; | |
} | |
let HashTable = function() { | |
let storage = []; | |
const storageLimit = 4; | |
this.add = function(key, value) { | |
let index = hash(key, storageLimit); | |
if (storage[index] === undefined) { | |
storage[index] = [ | |
[key, value] | |
]; | |
} else { | |
let inserted = false; | |
for (const element of storage[index]) { | |
if (element[0] === key) { | |
element[1] = value; | |
inserted = true; | |
} | |
} | |
if (inserted === false) { | |
storage[index].push([key, value]); | |
} | |
} | |
} | |
this.remove = function(key) { | |
let index = hash(key, storageLimit); | |
if (storage[index].length === 1 && storage[index][0][0] === key) { | |
delete storage[index][i]; | |
} else { | |
for (let i =0; i < storage[index]; i++) { | |
if (storage[index][i][0] === key) { | |
delete storage[index][i]; | |
} | |
} | |
} | |
} | |
this.lookup = function(key) { | |
let index = hash(key, storageLimit); | |
if (storage[index] === indefined) { | |
return undefined; | |
} else { | |
for ( i=0; i < storage[index].length; i++) { | |
if (storage[index][i][0] === key) { | |
return storage[index][1]; | |
} | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment