From 05f2708e4207350e83d2a5c67b5b16e8b860368f Mon Sep 17 00:00:00 2001 From: Manish Date: Thu, 24 Aug 2023 12:42:20 +1000 Subject: [PATCH] Data Structures: Create a Hash Table --- Data Structures/hashTable.js | 50 ++++++++++++++++++++++++++++++++++++ 1 file changed, 50 insertions(+) create mode 100644 Data Structures/hashTable.js 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 +};