Skip to content

Commit 1526e42

Browse files
committed
Added Simple Hash & Better Hash to Hash Table 🎨
1 parent 42857b1 commit 1526e42

File tree

2 files changed

+94
-0
lines changed

2 files changed

+94
-0
lines changed

examples/datastructures/hash-table.js

+47
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
class HashTable {
2+
constructor() {
3+
this.table = new Array(137);
4+
}
5+
6+
simpleHash(word) {
7+
let total = 0;
8+
for(let i = 0; i < word.length; i++)
9+
total += word.charCodeAt(i);
10+
return total % this.table.length;
11+
}
12+
13+
betterHash(word) {
14+
let total = 0;
15+
for(let i = 0; i < word.length; i++)
16+
total = 37 * total + word.charCodeAt(i);
17+
return total % this.table.length;
18+
}
19+
20+
put(value,whichHash) {
21+
let pos;
22+
if(whichHash == "simpleHash")
23+
pos = this.simpleHash(value);
24+
if(whichHash == "betterHash")
25+
pos = this.betterHash(value);
26+
this.table[pos] = value;
27+
}
28+
29+
get(value,whichHash) {
30+
let hash;
31+
if(whichHash == "simpleHash")
32+
hash = this.simpleHash(value);
33+
if(whichHash == "betterHash")
34+
hash = this.betterHash(value);
35+
return this.table[hash];
36+
}
37+
38+
showAll() {
39+
let str = "";
40+
for (let i = 0; i < this.table.length; i++)
41+
if(this.table[i] !=undefined)
42+
str += i + " : " + this.table[i] + "\n";
43+
return str;
44+
}
45+
}
46+
47+
module.exports = HashTable;
+47
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
const expect = require('chai').expect;
2+
const HashTable = require('../../examples/datastructures/hash-table');
3+
4+
describe('=> HASH TABLE', 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).to.deep.equal([]);
12+
done();
13+
});
14+
15+
describe('=> simpleHash', function() {
16+
before(function () {
17+
names = new HashTable();
18+
});
19+
20+
it('should put only 1 value of "Clayton" & "Raymond" in Hash Table bcz of Simple Hash', function(done) {
21+
names.put("Clayton","simpleHash");
22+
names.put("Raymond","simpleHash");
23+
expect(names.showAll()).to.equal("45 : Raymond\n");
24+
done();
25+
});
26+
27+
after(function() {
28+
names = new HashTable();
29+
});
30+
});
31+
32+
describe('=> betterHash', function() {
33+
it('should put both values of "Clayton" & "Raymond" in Hash Table bcz of Simple Hash', function(done) {
34+
names.put("Clayton","betterHash");
35+
names.put("Raymond","betterHash");
36+
expect(names.showAll()).to.equal("88 : Clayton\n92 : Raymond\n");
37+
done();
38+
});
39+
});
40+
41+
it('should get value from Hash Table',function() {
42+
names.put("New","betterHash");
43+
expect(names.get("New","betterHash")).to.equal("New");
44+
expect(names.get("xxx","betterHash")).to.equal(undefined);
45+
});
46+
47+
});

0 commit comments

Comments
 (0)