Skip to content

Instantly share code, notes, and snippets.

@BalasubramaniM
Last active October 2, 2018 08:16
Show Gist options
  • Save BalasubramaniM/cfc9487745434be665622ffbffe9e714 to your computer and use it in GitHub Desktop.
Save BalasubramaniM/cfc9487745434be665622ffbffe9e714 to your computer and use it in GitHub Desktop.
Data Structures: Create a Hash Table - freeCodeCamp
var called = 0;
var hash = string => {
called++;
var hash = 0;
for (var i = 0; i < string.length; i++) {
hash += string.charCodeAt(i);
}
return hash;
};
var HashTable = function() {
this.collection = {};
// change code below this line
this.add = (key, value) => {
let hashIndex = hash(key);
if (!this.collection[hashIndex]) {
this.collection[hashIndex] = {};
}
this.collection[hashIndex][key] = value;
};
this.remove = key => {
let hashIndex = hash(key);
if (!this.collection[hashIndex]) {
return null;
}
let objKeys = Object.keys(this.collection[hashIndex]);
for (let value of objKeys) {
if (value === key) {
delete this.collection[hashIndex];
// Here, I was trying to delete the particular value from the hashIndex like
// delete this.collection[hashIndex][value];
// But, It seems like, we need to delete the whole index if there are no values in hashIndex.
}
}
};
this.lookup = key => {
let hashIndex = hash(key);
if (!this.collection[hashIndex]) {
return null;
}
let objKeys = Object.keys(this.collection[hashIndex]);
for (let value of objKeys) {
if (value === key) {
return this.collection[hashIndex][value];
}
}
};
// change code above this line
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment