Hello,
I am struggling to pass https://learn.freecodecamp.org/coding-interview-prep/data-structures/create-a-hash-table/
my solution works for all my test although on the test page I get this error
’ The remove method accepts a key as input and removes the associated key value pair. ’
Any suggestions would be much appreciated.
Thank you
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 = function(key,value){
let inikey = key;
let hashed = hash(key);
let nmp = Object.create(null,{});
nmp[inikey] = value;
if(this.collection.hasOwnProperty(hashed)){
this.collection[hashed][inikey] = value;
return;
} else {
this.collection[hashed] = {};
this.collection[hashed][inikey] = value;
}
}
this.remove = function(key){
let inikey = key;
let hashed = hash(key);
if(hashed in this.collection){
delete this.collection[hashed][inikey];
if(Object.keys(this.collection[hashed]).length < 1){
delete this.collection[hashed];
}
} else {
console.log('is not');
return;
}
}
this.lookup = function(key){
let inikey = key;
let hashed = hash(key);
if(this.collection.hasOwnProperty(hashed)){
if(this.collection[hashed].hasOwnProperty(inikey)){
return this.collection[hashed][inikey];
}
}
// change code above this line
};
}
var test = new HashTable();
test.add('key1', 'value1');
test.add('1key', 'value2');
test.add('ke1y', 'value3');
test.add('new', 'fdsfdsg');
//test.remove('key1y'); // test for non existent key
//test.remove('new'); // remove element from the bucket and the bucket
//test.remove('ke1y'); //remove element from the bucket
test.remove('key1');
test.remove('new');
test.remove('1key');
console.log(test.collection);