forked from nas5w/javascript-patterns
-
Notifications
You must be signed in to change notification settings - Fork 0
/
hashTable.js
60 lines (52 loc) · 1.28 KB
/
hashTable.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
var LinkedList = require("./linkedList");
class HashTable {
constructor(length = 10, hashFunc) {
this._ds = new Array(length);
this.HashFunction = hashFunc ? hashFunc : this._hashFunc;
}
// Assume we are Hashing Strings
_hashFunc (data) {
if(typeof data === "object") {
data = JSON.stringify(data);
}
if (typeof data !== "string") {
data = data.toString();
}
return data.charCodeAt() % this._ds.length;
}
insert (data) {
var hashed = this.HashFunction(data);
if(!this._ds[hashed]) {
this._ds[hashed] = data;
return data + " added into base array at position " + hashed;
}
// Collision resolution using a linked list
var tmp = this._ds[hashed];
this._ds[hashed] = new LinkedList();
this._ds[hashed].insert(tmp);
return hashed + " added to linked list";
}
toString() {
let result = "";
this._ds.forEach(el => {
let data = typeof el === "object" ? el.toString() : el;
result +=`${data},\n`;
});
return result
.trim()
.substring(0, result.length - 2);
}
remove(data) {
let hashed = this.HashFunction(data);
if(!this._ds[hashed]) {
return -1;
}
if(typeof this._ds[hashed] === "object") {
this._ds[hashed].remove(data);
return hashed;
}
this._ds[hashed] = null;
return hashed;
}
}
module.exports = HashTable;