Hi! I can’t complete the ‘Create a Hash Table’ challenge from beta curriculum. It doesn’t pass any test, including the frist one, which is very strange and I can’t find the problem. Here’s my code:
var called = 0;
var hash = function(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 = function(key, value) {
var hashKey = hash(key);
if (this.collection.hasOwnProperty(hashKey)){
this.collection[hashKey].push({[key]: value});
} else {
this.collection[hashKey] = [];
this.collection[hashKey].push({[key]: value});
}
//console.log(this.collection);
};
this.lookup = function(key) {
var hashed = hash(key);
if (this.collection.hasOwnProperty(hashed)) {
var bucket = this.collection[hashed];
var find = function(index) {
if (bucket[index].hasOwnProperty(key)) {
return bucket[index][key];
} else if (index != 0) {
return find(index - 1);
} else {
return null;
};
};
return find(bucket.length - 1);
} else {
return null;
};
};
this.remove = function(key){
var hashed = hash(key);
if (this.collection.hasOwnProperty(hashed)){
if (this.collection[hashed].length === 1){
delete this.collection[hashed];
} else {
this.collection[hashed] = this.collection[hashed].filter(function(item){
return !item.hasOwnProperty(key);
});
}
} else {return null;}
};
// change code above this line
};