Skip to content

Instantly share code, notes, and snippets.

@jenjwong
Last active November 16, 2020 05:13
Show Gist options
  • Save jenjwong/14a164b6c138fc60eba9f9e2c56e4d56 to your computer and use it in GitHub Desktop.
Save jenjwong/14a164b6c138fc60eba9f9e2c56e4d56 to your computer and use it in GitHub Desktop.
class Hashtable {
constructor() {
this._storage = [];
this._storageLimit = 8;
}
insert(key, value) {
let hash = getHash(key, this._storageLimit);
this._storage[hash] ? this._storage[hash] = this._storage[hash] :
this._storage[hash] = [];
for (let i = 0; i < this._storage[hash].length; i++) {
let tupple = this._storage[hash][i];
if (tupple[0] === key) {
return 'key already exists; keys must be unique';
}
}
this._storage[hash].push([key, value]);
return 'inserted';
}
retrieve(key) {
let hash = getHash(key, this._storageLimit);
if (!this._storage[hash]) return 'key does not exist';
for (let i = 0; i < this._storage[hash].length; i++) {
let tupple = this._storage[hash][i];
if (tupple[0] === key) {
return tupple;
}
}
}
remove(key) {
let hash = getHash(key, this._storageLimit);
if (!this._storage[hash]) return 'key does not exist';
for (let i = 0; i < this._storage[hash].length; i++) {
if (this._storage[hash][i][0] === key) {
this._storage[hash][i].splice(i, 2);
return key + ' removed';
}
}
}
};
// helper function that generates hash
var getHash = function (str, max) {
let hash = 0;
for (let i = 0; i < str.length; i++) {
hash = (hash << 5) + hash + str.charCodeAt(i);
hash = hash & hash; //
hash = Math.abs(hash);
}
return hash % max;
};
@darrylsepeda
Copy link

hi @jenjwong, I have a question, I tried your code and it works fine.. but when I tried to look deeper, getHash function always return 0, so I remove the getHash func and it still works. Can you explain why the getHash always return 0, and what is that used for?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment