@@ -14,6 +14,7 @@ class HashTable {
14
14
this . allowResize = allowResize ;
15
15
this . strongHash = strongHash ;
16
16
if ( custonHash ) {
17
+ // eslint-disable-next-line no-underscore-dangle
17
18
this . _hash = custonHash ;
18
19
}
19
20
@@ -108,6 +109,21 @@ class HashTable {
108
109
return res ;
109
110
}
110
111
112
+ // eslint-disable-next-line class-methods-use-this
113
+ _convertNodesToSLL ( nodeCollection ) {
114
+ // convert collection of nodes into a SLL
115
+ let head = nodeCollection [ 0 ] ;
116
+ const start = head ;
117
+ let i = 1 ;
118
+ while ( i < nodeCollection . length ) {
119
+ head . next = nodeCollection [ i ] ;
120
+ i += 1 ;
121
+ head = head . next ;
122
+ }
123
+
124
+ return start ;
125
+ }
126
+
111
127
set ( key , value ) {
112
128
// eslint-disable-next-line no-underscore-dangle
113
129
const index = this . _hash ( key ) ;
@@ -143,7 +159,6 @@ class HashTable {
143
159
144
160
// get the SLL using the index
145
161
let head = this . bucket [ index ] ;
146
-
147
162
// return null if the head is null
148
163
if ( ! head ) {
149
164
return null ;
@@ -152,17 +167,19 @@ class HashTable {
152
167
// get all the values for the key to return
153
168
// eslint-disable-next-line no-underscore-dangle
154
169
const vals = this . _values ( index , key ) ;
155
-
156
- let newHead = null ; // to hold the start of the new SLL
170
+ const nodes = [ ] ;
157
171
while ( head !== null ) {
158
- if ( head . key === key ) {
159
- // we have to delete current node
160
- newHead = head . next ;
172
+ if ( head . key !== key ) {
173
+ nodes . push ( new HashEntry ( { key : head . key , value : head . value } ) ) ;
161
174
}
162
175
head = head . next ;
163
176
}
177
+
178
+ // eslint-disable-next-line no-underscore-dangle
179
+ const sll = this . _convertNodesToSLL ( nodes ) ;
180
+
181
+ this . bucket [ index ] = sll ;
164
182
// update the index with the lastest head value
165
- this . bucket [ index ] = newHead ;
166
183
return { key : vals } ;
167
184
}
168
185
@@ -171,18 +188,16 @@ class HashTable {
171
188
}
172
189
173
190
isEmpty ( ) {
174
- return this . getSize ( ) === 0 ;
191
+ return this . size === 0 ;
175
192
}
176
193
}
177
194
178
- // const ht = new HashTable(5);
179
- // console.log('HT slots = ', ht.slot);
195
+ // const ht = new HashTable(5, { allowResize: false, strongHash: false });
180
196
// ht.set('maroon', 'I maroon');
181
197
// ht.set('hello', 'I am a new value');
182
- // console.log(ht.bucket);
198
+ // // console.log(ht.bucket);
183
199
// ht.set('hell', 'Bad value');
184
200
// ht.set('hello', 'I am a yet another value');
185
- // console.log('HT slots = ', ht.slot);
186
201
// ht.set('yellow', 'I am yellow');
187
202
188
203
// // console.log(ht.get('hello'));
0 commit comments