51 lines
1.2 KiB
JavaScript
51 lines
1.2 KiB
JavaScript
// https://www.freecodecamp.org/learn/coding-interview-prep/data-structures/create-a-hash-table
|
|
|
|
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 = (k, v) => {
|
|
const keyHash = hash(k);
|
|
if (this.collection[keyHash] === undefined) {
|
|
this.collection[keyHash] = [[k, v]];
|
|
} else {
|
|
this.collection[keyHash].push([k, v]);
|
|
}
|
|
};
|
|
|
|
this.remove = (k) => {
|
|
const keyHash = hash(k);
|
|
if (this.collection[keyHash] === undefined) {
|
|
return;
|
|
}
|
|
this.collection[keyHash] = this.collection[keyHash].filter(
|
|
([key, value]) => key !== k
|
|
);
|
|
if (this.collection[keyHash].length === 0) {
|
|
delete this.collection[keyHash];
|
|
}
|
|
};
|
|
|
|
this.lookup = (k) => {
|
|
const keyHash = hash(k);
|
|
if (this.collection[keyHash] === undefined) {
|
|
return null;
|
|
}
|
|
for (let [key, value] of this.collection[keyHash]) {
|
|
if (key === k) {
|
|
return value;
|
|
}
|
|
}
|
|
return null;
|
|
};
|
|
// Only change code above this line
|
|
};
|