Hash Table

Run Settings
LanguageJavaScript
Language Version
Run Command
class Hash{ constructor(size){ this.data = new Array(size); } _hash(key) { let hash = 0; for(let i=0;i<key.length;i++) { hash = (hash+key.charCodeAt(i)*i)%this.data.length; } return hash; } set(key,value) { let index = this._hash(key); if(!this.data[index]) this.data[index] = []; this.data[index].push([key,value]); } get(key) { let index = this._hash(key); let currentBucket = this.data[index]; if(currentBucket.length) { for(let i=0;i<currentBucket.length;i++) { if(currentBucket[i][0]==key) return currentBucket[i][1] } } return undefined; } keys(){ let keysArray=[]; for(let i=0;i<this.data.length;i++) { for(let j=0;j<this.data[i].length;j++) keysArray.push(this.data[i][j][0]) } return keysArray; } } let obj = new Hash(); obj.set('grapes',10000); obj.set('oranges',4) obj.set('apples',20000); console.log(obj.get('apples')) console.log(obj.keys())
Editor Settings
Theme
Key bindings
Full width
Lines