Skip to content

Commit 1c9e475

Browse files
committed
Hash Table using Separate Chaining 🐛
1 parent ac77040 commit 1c9e475

File tree

2 files changed

+74
-0
lines changed

2 files changed

+74
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
class HashTable {
2+
constructor() {
3+
this.table = new Array(137);
4+
this.buildChains();
5+
}
6+
7+
betterHash(word) {
8+
let total = 0;
9+
for(let i = 0; i < word.length; i++)
10+
total = 37 * total + word.toLowerCase().charCodeAt(i);
11+
return total % this.table.length;
12+
}
13+
14+
buildChains() {
15+
for (let i = 0; i < this.table.length; i++)
16+
this.table[i] = [];
17+
}
18+
19+
put(value) {
20+
const pos = this.betterHash(value);
21+
let index = 0;
22+
while(index < this.table.length && this.table[pos][index] != undefined)
23+
index++;
24+
this.table[pos][index] = value;
25+
}
26+
27+
get(value) {
28+
const hash = this.betterHash(value);
29+
let index = 0;
30+
while(index < this.table.length && this.table[hash][index] != value)
31+
index++;
32+
return this.table[hash][index];
33+
}
34+
35+
showAll() {
36+
let str = "";
37+
for (let i = 0; i < this.table.length && this.table[i] !=undefined; i++)
38+
for (let j = 0; j < this.table[i].length && this.table[i][j] !=undefined; j++)
39+
str += i + " : " + this.table[i] + "\n";
40+
return str;
41+
}
42+
}
43+
44+
module.exports = HashTable;
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
const expect = require('chai').expect;
2+
const HashTable = require('../../examples/datastructures/hash-table-separate-chaining');
3+
4+
describe('=> HASH TABLE USING SEPARATE CHAINING', function() {
5+
let names;
6+
before(function () {
7+
names = new HashTable();
8+
});
9+
10+
it('should create an Empty Hash Table', function(done) {
11+
expect(names.table.length).to.deep.equal(137);
12+
done();
13+
});
14+
15+
it('should put value into the Hash Table',function() {
16+
names.put("Diana");
17+
names.put("Clayton");
18+
names.put("Raymond");
19+
names.put("Nadia");
20+
names.put("Afzar");
21+
expect(names.showAll()).to.equal("11 : Diana\n41 : Afzar\n56 : Clayton\n60 : Raymond\n129 : Nadia\n");
22+
});
23+
24+
it('should get value from the Hash Table',function() {
25+
expect(names.get("Nadia")).to.equal("Nadia");
26+
expect(names.get("Diana")).to.equal("Diana");
27+
expect(names.get("Azhar")).to.equal(undefined);
28+
});
29+
30+
});

0 commit comments

Comments
 (0)