-
Notifications
You must be signed in to change notification settings - Fork 0
/
chp7-hashs.js
80 lines (68 loc) · 2.25 KB
/
chp7-hashs.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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
function MyMap() {
var items = {}; // like set using an object to implement Map/Dictionary
this.contains = x => items.hasOwnProperty(x);
this.add = (key, val) => {
if (!this.contains(key)){
items[key] = val;
return true;
}
return false;
}
this.remove = key => {
if (this.contains(key)) {
delete items[key];
return true;
}
return false;
}
this.clear = () => items = {};
this.size = () => Object.keys(items).length;
this.keys = () => Object.keys(items);
this.get = key => this.contains(key) ? items[key] : undefined;
this.values = () => {
var keys = this.keys();
var res = [];
keys.forEach(k => res.push(items[k]));
return res;
}
}
var djb2 = function(key) {
var hash = 5381;
for (var i = 0; i < key.length; i++) {
hash = (hash * 33) + key.charCodeAt(i);
}
return hash % 1013;
}
// a key value pair that is to be added to the hash table.
function KeyValuePair(key, value) {
this.Key = key;
this.Value = value;
this.toString = () => {
return key + '-' + value;
}
}
function HashTable(capacity = 4) {
var buckets = new Array(capacity);
// use separate chainning to handle collisions
this.addSC = (key, value) => {
var hashedKey = djb2(key);
if (buckets[hashedKey] === undefined) {
// first time to insert to this index, initilise it to a new single LinkedList
buckets[hashedKey] = new LinkedList();
}
// when colision happens; just add it to the list
buckets[hashedKey].append(new KeyValuePair(key, value));
}
// use linear probing to handle collisions
this.addLP = (key, value) => {
var hashedKey = djb2(key);
var currentItem = buckets[hashedKey];
while (!currentItem) {
hashedKey++; // keep incrementing the hashed key until there is a space available.
currentItem = buckets[hashedKey];
}
buckets[hashedKey] = new KeyValuePair(key, value);
}
}
console.log(djb2('tiantang sun'));
console.log(djb2('tony sun'));