@@ -3,10 +3,12 @@ const HashEntry = require('./HashEntry');
3
3
class HashTable {
4
4
constructor ( slots ) {
5
5
// init with a default set of slots
6
- this . slot = slots || 17 ;
6
+ this . slot = slots || 19 ;
7
7
// size to hold the current size
8
8
// and help to resize when the table is half filled
9
9
this . size = 0 ;
10
+ // threshold (let it be 70%)
11
+ this . threshold = 0.7 ;
10
12
// the main bucket
11
13
this . bucket = new Array ( this . slot ) ;
12
14
@@ -32,6 +34,34 @@ class HashTable {
32
34
return index ;
33
35
}
34
36
37
+ _resize ( ) {
38
+ const oldSlot = this . slot ;
39
+ const oldBucket = this . bucket ;
40
+
41
+ this . slot = oldSlot * 2 ;
42
+ const newBucket = new Array ( this . slot ) ;
43
+ // fill the new bucket with nulls
44
+ for ( let i = 0 ; i < this . slot ; i += 1 ) newBucket [ i ] = null ;
45
+
46
+ this . bucket = newBucket ;
47
+
48
+ for ( let i = 0 ; i < oldSlot ; i += 1 ) {
49
+ if ( oldBucket [ i ] ) {
50
+ // get all the nodes associated here
51
+ let head = oldBucket [ i ] ;
52
+
53
+ while ( head !== null ) {
54
+ const { key, value } = head ;
55
+ // eslint-disable-next-line no-underscore-dangle
56
+ const newIndex = this . _hash ( key ) ;
57
+ // eslint-disable-next-line no-underscore-dangle
58
+ this . _push ( newIndex , { key, value } ) ;
59
+ head = head . next ;
60
+ }
61
+ }
62
+ }
63
+ }
64
+
35
65
_push ( index , value ) {
36
66
/**
37
67
* Util to add a SSL to the index in case of more than once
@@ -76,6 +106,17 @@ class HashTable {
76
106
// storing value as an key-value pair
77
107
// eslint-disable-next-line no-underscore-dangle
78
108
this . _push ( index , { key, value } ) ;
109
+
110
+ /**
111
+ * calculate the load factor, if it's greater than threshold
112
+ * resize the hash table
113
+ */
114
+ const loadFactor = ( this . size / this . slot ) . toFixed ( 1 ) ;
115
+ if ( loadFactor > this . threshold ) {
116
+ // console.log('Resizing hash table');
117
+ // eslint-disable-next-line no-underscore-dangle
118
+ this . _resize ( ) ;
119
+ }
79
120
}
80
121
81
122
get ( key ) {
0 commit comments