@@ -84,29 +84,33 @@ class HashTable {
84
84
}
85
85
86
86
let head = this . bucket [ index ] ;
87
+ // extract the key and see if it already exists
88
+ const { key, value : newValue } = value ;
87
89
88
90
// traverse to the end
89
91
while ( head . next !== null ) {
92
+ if ( head . key === key ) {
93
+ // overridet the value with the new value
94
+ head . value = newValue ;
95
+ return index ;
96
+ }
90
97
head = head . next ;
91
98
}
99
+ // if the key was not found
92
100
head . next = node ;
93
101
this . size += 1 ;
94
102
return index ;
95
103
}
96
104
97
- _values ( index , key ) {
98
- /**
99
- * Utility to return the values as an array for a given key
100
- */
101
- const res = [ ] ;
105
+ _value ( index , key ) {
102
106
let head = this . bucket [ index ] ;
103
107
while ( head !== null ) {
104
108
if ( head . key === key ) {
105
- res . push ( head . value ) ;
109
+ return head . value ;
106
110
}
107
111
head = head . next ;
108
112
}
109
- return res ;
113
+ return null ;
110
114
}
111
115
112
116
// eslint-disable-next-line class-methods-use-this
@@ -149,7 +153,7 @@ class HashTable {
149
153
const index = this . _hash ( key ) ;
150
154
if ( ! this . bucket [ index ] ) return null ;
151
155
// eslint-disable-next-line no-underscore-dangle
152
- return this . _values ( index , key ) ;
156
+ return this . _value ( index , key ) ;
153
157
}
154
158
155
159
remove ( key ) {
@@ -187,6 +191,7 @@ class HashTable {
187
191
previous = head ;
188
192
head = head . next ;
189
193
}
194
+ return null ;
190
195
}
191
196
192
197
getSize ( ) {
@@ -201,13 +206,13 @@ class HashTable {
201
206
// const ht = new HashTable(5, { allowResize: false, strongHash: false });
202
207
// ht.set('maroon', 'I maroon');
203
208
// ht.set('hello', 'I am a new value');
204
- // // console.log(ht.bucket);
209
+ // console.log(ht.bucket);
205
210
// ht.set('hell', 'Bad value');
206
- // // ht.set('hello', 'I am a yet another value');
211
+ // ht.set('hello', 'I am a yet another value');
207
212
// ht.set('yellow', 'I am yellow');
208
213
209
- // // console.log(ht.get('hello'));
210
- // // console.log(ht.get('maroon'));
214
+ // console.log(ht.get('hello'));
215
+ // console.log(ht.get('maroon'));
211
216
// console.log(ht.bucket);
212
217
213
218
// console.log('deleting hello........');
0 commit comments