Skip to content

Instantly share code, notes, and snippets.

@S-codes14
Created May 22, 2021 04:12
Show Gist options
  • Save S-codes14/4eda84fdecabbc8d1a080d8397e7ddb7 to your computer and use it in GitHub Desktop.
Save S-codes14/4eda84fdecabbc8d1a080d8397e7ddb7 to your computer and use it in GitHub Desktop.
Hash table in js
/* Hash Table */
var hash = (string, max) => {
var hash = 0;
for (var i = 0; i < string.length; i++) {
hash += string.charCodeAt(i);
}
return hash % max;
};
let HashTable = function() {
let storage = [];
const storageLimit = 14;
this.print = function() {
console.log(storage)
}
this.add = function(key, value) {
var index = hash(key, storageLimit);
if (storage[index] === undefined) {
storage[index] = [
[key, value]
];
} else {
var inserted = false;
for (var i = 0; i < storage[index].length; i++) {
if (storage[index][i][0] === key) {
storage[index][i][1] = value;
inserted = true;
}
}
if (inserted === false) {
storage[index].push([key, value]);
}
}
};
this.remove = function(key) {
var index = hash(key, storageLimit);
if (storage[index].length === 1 && storage[index][0][0] === key) {
delete storage[index];
} else {
for (var i = 0; i < storage[index].length; i++) {
if (storage[index][i][0] === key) {
delete storage[index][i];
}
}
}
};
this.lookup = function(key) {
var index = hash(key, storageLimit);
if (storage[index] === undefined) {
return undefined;
} else {
for (var i = 0; i < storage[index].length; i++) {
if (storage[index][i][0] === key) {
return storage[index][i][1];
}
}
}
};
};
console.log(hash('quincy', 10))
let ht = new HashTable();
ht.add('beau', 'person');
ht.add('fido', 'dog');
ht.add('rex', 'dinosour');
ht.add('tux', 'penguin')
console.log(ht.lookup('tux'))
ht.print();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment