Tell us what’s happening:
I can’t pass the test regarding collisions. Even though I’ve checked in the console and the program takes into account collisions and works fine, when i run the tests it just fails.
Does anyone have any idea what I’m doing wrong?
Your code so far
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 = {};
this.add = function(key, value) {
var hashed = hash(key);
if (!this.collection.hasOwnProperty(hashed)) {
this.collection[hashed] = [];
this.collection[hashed].push([key, value]);
} else {
var match = false;
for (var i = 0; i < this.collection[hashed].length; i++) {
if (this.collection[hashed][i][0] == key) {
this.collection[hashed][i][1] = value;
match = true;
}
}
if (!match) {
this.collection[hashed].push([key, value]);
}
}
};
this.remove = function(key) {
var hashed = hash(key);
for (var j = 0; j < this.collection[hashed].length; j++) {
if (this.collection[hashed][j][0] == key) {
var deleted = this.collection[hashed].splice(j, 1);
}
}
};
this.lookup = function(key) {
var hashed = hash(key);
for (let elem in this.collection[hashed]) {
if (this.collection[hashed][elem][0] == key) {
return this.collection[hashed][elem][1];
}
return null;
}
};
}
Your browser information:
User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.117 Safari/537.36
.
Challenge: Create a Hash Table
Link to the challenge:
https://www.freecodecamp.org/learn/coding-interview-prep/data-structures/create-a-hash-table