Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit ea7853e

Browse files
committed
update: override the value for same key
1 parent cffd6e2 commit ea7853e

File tree

1 file changed

+17
-12
lines changed

1 file changed

+17
-12
lines changed

‎src/_DataStructures_/HashTable/index.js‎

Lines changed: 17 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -84,29 +84,33 @@ class HashTable {
8484
}
8585

8686
let head = this.bucket[index];
87+
// extract the key and see if it already exists
88+
const { key, value: newValue } = value;
8789

8890
// traverse to the end
8991
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+
}
9097
head = head.next;
9198
}
99+
// if the key was not found
92100
head.next = node;
93101
this.size += 1;
94102
return index;
95103
}
96104

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) {
102106
let head = this.bucket[index];
103107
while (head !== null) {
104108
if (head.key === key) {
105-
res.push(head.value);
109+
returnhead.value;
106110
}
107111
head = head.next;
108112
}
109-
return res;
113+
return null;
110114
}
111115

112116
// eslint-disable-next-line class-methods-use-this
@@ -149,7 +153,7 @@ class HashTable {
149153
const index = this._hash(key);
150154
if (!this.bucket[index]) return null;
151155
// eslint-disable-next-line no-underscore-dangle
152-
return this._values(index, key);
156+
return this._value(index, key);
153157
}
154158

155159
remove(key) {
@@ -187,6 +191,7 @@ class HashTable {
187191
previous = head;
188192
head = head.next;
189193
}
194+
return null;
190195
}
191196

192197
getSize() {
@@ -201,13 +206,13 @@ class HashTable {
201206
// const ht = new HashTable(5, { allowResize: false, strongHash: false });
202207
// ht.set('maroon', 'I maroon');
203208
// ht.set('hello', 'I am a new value');
204-
// // console.log(ht.bucket);
209+
// console.log(ht.bucket);
205210
// 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');
207212
// ht.set('yellow', 'I am yellow');
208213

209-
// // console.log(ht.get('hello'));
210-
// // console.log(ht.get('maroon'));
214+
// console.log(ht.get('hello'));
215+
// console.log(ht.get('maroon'));
211216
// console.log(ht.bucket);
212217

213218
// console.log('deleting hello........');

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /