-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathHash_Table_Resizing.js
More file actions
93 lines (81 loc) · 2.1 KB
/
Hash_Table_Resizing.js
File metadata and controls
93 lines (81 loc) · 2.1 KB
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
81
82
83
84
85
86
87
88
89
90
91
92
93
//Hash Table Resizing
//Define a resize function in the following hash table implementation.
var makeHashTable = function(){
var result = {};
var storage = [];
var storageLimit = 4;
var size = 0;
var resizing = false;
function resize(newSize){
var newStorage = storage;
storageLimit = newSize;
newStorage.forEach(function(bucket){
bucket.forEach(function(pair){
result.insert(pair[0], pair[1]);
});
});
}
result.insert = function(key, value){
var index = getIndexBelowMaxForKey(key, storageLimit);
storage[index] = storage[index] || [];
var pairs = storage[index];
var pair;
var replaced = false;
for (var i = 0; i < pairs.length; i++) {
pair = pairs[i];
if (pair[0] === key) {
pair[1] = value;
replaced = true;
}
}
if (!replaced) {
pairs.push([key, value]);
size++;
}
if(size >= storageLimit * 0.75){
// increase the size of the hash table
resize(storageLimit * 2);
}
};
result.retrieve = function(key){
var index = getIndexBelowMaxForKey(key, storageLimit);
var pairs = storage[index];
if (!pairs) { return; }
var pair;
for (var i = 0; i < pairs.length; i++) {
pair = pairs[i];
if (pair && pair[0] === key) {
return pair[1];
}
}
};
result.remove = function(key){
var index = getIndexBelowMaxForKey(key, storageLimit);
var pairs = storage[index];
var pair;
for (var i = 0; i < pairs.length; i++) {
pair = pairs[i];
if (pair[0] === key) {
var value = pair[1];
delete pairs[i];
size--;
if(size <= storageLimit * 0.25){
// decrease the size of the hash table
resize(storageLimit / 2);
}
return value;
}
}
};
return result;
};
// This is a "hashing function".
var getIndexBelowMaxForKey = function(str, max){
var hash = 0;
for (var i = 0; i < str.length; i++) {
hash = (hash<<5) + hash + str.charCodeAt(i);
hash = hash & hash; // Convert to 32bit integer
hash = Math.abs(hash);
}
return hash % max;
};