Data Structures: Create a Hash Table
This commit is contained in:
parent
a08d964b1a
commit
05f2708e42
50
Data Structures/hashTable.js
Normal file
50
Data Structures/hashTable.js
Normal file
@ -0,0 +1,50 @@
|
||||
// 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
|
||||
};
|
Loading…
Reference in New Issue
Block a user