Created
November 29, 2018 01:33
-
-
Save deadkff01/e1e7c8734e4006060e88f04b27e71fed to your computer and use it in GitHub Desktop.
HashTable with JavaScript
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class HashTable{ | |
constructor(size=42){ | |
this.buckets = new Array(size) | |
this.size = size | |
} | |
hash(key){ | |
return key.toString().length % this.size; | |
} | |
set(key,value){ | |
let index = this.hash(key); | |
if(!this.buckets[index]){ | |
this.buckets[index] = []; | |
} | |
this.buckets[index].push([key,value]) | |
return index | |
} | |
get(key){ | |
let index = this.hash(key); | |
if(!this.buckets[index])return null | |
for(let bucket of this.buckets[index]){ | |
// key | |
if(bucket [0] === key){ | |
//value | |
return bucket [1] | |
} | |
} | |
} | |
} | |
mocha.setup('bdd'); | |
var assert = chai.assert; | |
describe('Hash tables',()=>{ | |
it("should add the new data ",()=>{ | |
const hasht = new HashTable(10); | |
hasht.set("userId3","pop") | |
hasht.set("userId4","king") | |
hasht.set("userId9","april") | |
hasht.set("userId50","gowtham") | |
hasht.set("userId100","olo") | |
assert.deepEqual([["userId3", "pop"], ["userId4", "king"], ["userId9", "april"]],hasht.buckets[7]) | |
}) | |
it("should get the value ",()=>{ | |
const hasht = new HashTable(10); | |
hasht.set("userId3","pop") | |
hasht.set("userId4","king") | |
hasht.set("userId9","april") | |
hasht.set("userId50","gowtham") | |
hasht.set("userId100","olo") | |
assert.equal("gowtham",hasht.get("userId50")) | |
assert.equal("pop",hasht.get("userId3")) | |
assert.equal("king",hasht.get("userId4")) | |
assert.equal("olo",hasht.get("userId100")) | |
assert.equal("april",hasht.get("userId9")) | |
}) | |
}) | |
mocha.run() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment