HashTables

Run Settings
LanguageJavascript
Language Version
Run Command
class HashTable { constructor(size) { this.data = new Array(size); } //Time complexity //O(1) _hash(key) { let hash = 0; for(let i = 0; i < key.length; i++) { hash = (hash + key.charCodeAt(i) * i) % this.data.length; } return hash; } //Time complexity //O(1) set(key,value) { let address = this._hash(key); if(!this.data[address]) { this.data[address] = []; } this.data[address].push([key,value]); return this.data; } //Time complexity //O(1) //O(n) if there are collisions get(key) { let address = this._hash(key); const currentBucket = this.data[address]; if(currentBucket) { for(let i = 0; i < currentBucket.length; i++) { if(currentBucket[i][0] === key) { return currentBucket[i][1]; } } } return undefined; } keys() { if(!this.data.length) { return undefined; } const keysArray = []; for(let i = 0; i < this.data.length;i++) { if(this.data[i])//if data exists { keysArray.push(this.data[i][0][0]); } } return keysArray; } } const myHashTable = new HashTable(100); myHashTable.set("grapes",5); myHashTable.set("apples",12); myHashTable.set("pears",20); console.log(myHashTable.get("grapes")); console.log(myHashTable.keys());
function firstRecurring(input) { for(let i = 0; i < input.length; i++) { for(let j = i+1; j < input.length; j++) { if(input[i] === input[j]) { return input[i]; } } } return undefined; } function firstRecurring2(input) { let map = {}; for(let i = 0; i < input.length; i++) { if(map[input[i]] !== undefined) { return input[i]; } } return undefined; }
Editor Settings
Theme
Key bindings
Full width
Lines