@@ -129,6 +129,34 @@ class HashTable {
129
129
return this . _values ( index , key ) ;
130
130
}
131
131
132
+ delete ( key ) {
133
+ // get the index
134
+ // eslint-disable-next-line no-underscore-dangle
135
+ const index = this . _hash ( key ) ;
136
+
137
+ // get the SLL using the index
138
+ let head = this . bucket [ index ] ;
139
+
140
+ // return null if the head is null
141
+ if ( ! head ) {
142
+ return null ;
143
+ }
144
+
145
+ // get all the values for the key to return
146
+ // eslint-disable-next-line no-underscore-dangle
147
+ const vals = this . _values ( index , key ) ;
148
+
149
+ while ( head !== null ) {
150
+ if ( head . key === key ) {
151
+ // we have to delete current node
152
+ head = head . next ;
153
+ }
154
+ }
155
+ // update the index with the lastest head value
156
+ this . bucket [ index ] = head ;
157
+ return vals ;
158
+ }
159
+
132
160
getSize ( ) {
133
161
return this . size ;
134
162
}
@@ -138,18 +166,22 @@ class HashTable {
138
166
}
139
167
}
140
168
141
- const ht = new HashTable ( 5 ) ;
142
- console . log ( 'HT slots = ' , ht . slot ) ;
143
- ht . set ( 'maroon' , 'I maroon' ) ;
144
- ht . set ( 'hello' , 'I am a new value' ) ;
145
- console . log ( ht . bucket ) ;
146
- ht . set ( 'hell' , 'Bad value' ) ;
147
- ht . set ( 'hello' , 'I am a yet another value' ) ;
148
- console . log ( 'HT slots = ' , ht . slot ) ;
149
- ht . set ( 'yellow' , 'I am yellow' ) ;
150
-
151
- // console.log(ht.get('hello'));
152
- // console.log(ht.get('maroon'));
153
- console . log ( ht . bucket ) ;
169
+ // const ht = new HashTable(5);
170
+ // console.log('HT slots = ', ht.slot);
171
+ // ht.set('maroon', 'I maroon');
172
+ // ht.set('hello', 'I am a new value');
173
+ // console.log(ht.bucket);
174
+ // ht.set('hell', 'Bad value');
175
+ // ht.set('hello', 'I am a yet another value');
176
+ // console.log('HT slots = ', ht.slot);
177
+ // ht.set('yellow', 'I am yellow');
178
+
179
+ // // console.log(ht.get('hello'));
180
+ // // console.log(ht.get('maroon'));
181
+ // console.log(ht.bucket);
182
+
183
+ // console.log('deleting hello........');
184
+ // ht.delete('hello');
185
+ // console.log(ht.bucket);
154
186
155
187
module . exports = HashTable ;
0 commit comments