diff --git a/Data Structures/hashTable.js b/Data Structures/hashTable.js new file mode 100644 index 0000000..a3f0e7b --- /dev/null +++ b/Data Structures/hashTable.js @@ -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 +};