Skip to content

Instantly share code, notes, and snippets.

@adames
Last active May 13, 2023 18:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save adames/bb731f2062ced67b1c3d26356468b237 to your computer and use it in GitHub Desktop.
Save adames/bb731f2062ced67b1c3d26356468b237 to your computer and use it in GitHub Desktop.
simple hash table
// 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