1
1
const HashEntry = require ( './HashEntry' ) ;
2
2
3
3
class HashTable {
4
- constructor ( slots ) {
4
+ constructor ( slots , { allowResize = true , strongHash = true , custonHash = null } ) {
5
5
// init with a default set of slots
6
6
this . slot = slots || 19 ;
7
7
// size to hold the current size
@@ -11,6 +11,11 @@ class HashTable {
11
11
this . threshold = 0.7 ;
12
12
// the main bucket
13
13
this . bucket = new Array ( this . slot ) ;
14
+ this . allowResize = allowResize ;
15
+ this . strongHash = strongHash ;
16
+ if ( custonHash ) {
17
+ this . _hash = custonHash ;
18
+ }
14
19
15
20
// fill the bucket with null
16
21
for ( let i = 0 ; i < this . slot ; i += 1 ) this . bucket [ i ] = null ;
@@ -31,7 +36,9 @@ class HashTable {
31
36
const char = stringKey [ i ] ;
32
37
const value = char . charCodeAt ( 0 ) - 96 ;
33
38
index = ( index * PRIME_MULTIPLIER + value ) % this . bucket . length ;
34
- index = ( index + PRIME_ADDER ) % this . bucket . length ;
39
+ if ( this . strongHash ) {
40
+ index = ( index + PRIME_ADDER ) % this . bucket . length ;
41
+ }
35
42
}
36
43
return index ;
37
44
}
@@ -113,7 +120,7 @@ class HashTable {
113
120
* resize the hash table
114
121
*/
115
122
const loadFactor = Number ( ( this . size / this . slot ) . toFixed ( 1 ) ) ;
116
- if ( loadFactor > this . threshold ) {
123
+ if ( loadFactor > this . threshold && this . allowResize ) {
117
124
// console.log('Resizing hash table');
118
125
// eslint-disable-next-line no-underscore-dangle
119
126
this . _resize ( ) ;
@@ -146,15 +153,17 @@ class HashTable {
146
153
// eslint-disable-next-line no-underscore-dangle
147
154
const vals = this . _values ( index , key ) ;
148
155
156
+ let newHead = null ; // to hold the start of the new SLL
149
157
while ( head !== null ) {
150
158
if ( head . key === key ) {
151
159
// we have to delete current node
152
- head = head . next ;
160
+ newHead = head . next ;
153
161
}
162
+ head = head . next ;
154
163
}
155
164
// update the index with the lastest head value
156
- this . bucket [ index ] = head ;
157
- return vals ;
165
+ this . bucket [ index ] = newHead ;
166
+ return { key : vals } ;
158
167
}
159
168
160
169
getSize ( ) {
@@ -181,7 +190,7 @@ class HashTable {
181
190
// console.log(ht.bucket);
182
191
183
192
// console.log('deleting hello........');
184
- // ht.delete ('hello');
193
+ // console.log( ht.remove ('hello') );
185
194
// console.log(ht.bucket);
186
195
187
196
module . exports = HashTable ;
0 commit comments