I cannot see where my error is.
I’m trying to solve Coding Interview Prep > Data Structures> Create a Hash Table
My code is as follow:
var called = 0;
var hash = string => {
called++;
var hashed = 0;
for (var i = 0; i < string.length; i++) {
hashed += string.charCodeAt(i);
}
return hashed;
};
var HashTable = function() {
this.collection = {};
// Only change code below this line
this.add = function(key, value) {
let h = hash(key);
if (this.collection.hasOwnProperty(h)) {
let prop = [key, value];
this.collection[h].push(prop);
} else {
this.collection[h] = [];
this.collection[h].push([key, value]);
}
}
this.remove = function(key) {
let h = hash(key);
if (this.collection.hasOwnProperty(h)) {
let value = this.collection[h];
for (let i = 0; i < value.length; i++) {
if (value[i][0] == key) {
value.splice(i, 1);
this.collection[h] = value;
break;
}
}
if (value.length == 0) {
delete this.collection[h];
}
}
}
this.lookup = function(key) {
let result = this.collection[hash(key)];
if (result != undefined) {
for (let elem of result) {
if (elem[0] == key) {
return elem[1];
}
}
}
return null;
}
// Only change code above this line
};
// tests
var hs = new HashTable();
console.log(hs);
console.log("");
hs.add("alfa", "ventuno");
console.log("add alfa:\n", hs.collection);
console.log("");
hs.add("beta", "ventidue");
console.log("add beta:\n", hs.collection);
console.log("");
hs.add("gamma", "ventitre");
console.log("add gamma:\n", hs.collection);
console.log("");
hs.add("ammag", "venticinque");
console.log("add ammag (collision):\n", hs.collection);
console.log("");
hs.add("ateb", "ventiquattro");
console.log("add ateb (collision):\n", hs.collection);
console.log("");
console.log("log beta:", hs.lookup("beta"))
console.log("log ateb:", hs.lookup("ateb"))
console.log("log gamma:", hs.lookup("gamma"))
console.log("log ammag:", hs.lookup("ammag"))
console.log("");
hs.remove("beta");
console.log("remove beta:\n", hs.collection);
console.log("");
hs.remove("ammag");
console.log("remove ammag:\n", hs.collection);
console.log("");
console.log("log beta:", hs.lookup("beta"))
console.log("log ateb:", hs.lookup("ateb"))
console.log("log gamma:", hs.lookup("gamma"))
console.log("log ammag:", hs.lookup("ammag"))
console.log("");
As usual, I added some tests to visualize the code behavior, and all the tests give the results that one expects.
But the sistem test return the following error:
The remove method should accept a key as input and
should remove the associated key value pair.
Well, it seems to me that the remove
method actually accept a key and remove the associated key-value pair, as you can see following the tests.
Can you please give me a hint to find my error?