Skip to content

Commit 2060a13

Browse files
committed
update: delete key of hash table
1 parent 22c6465 commit 2060a13

File tree

1 file changed

+45
-13
lines changed

1 file changed

+45
-13
lines changed

src/_DataStructures_/HashTable/index.js

+45-13
Original file line numberDiff line numberDiff line change
@@ -129,6 +129,34 @@ class HashTable {
129129
return this._values(index, key);
130130
}
131131

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+
132160
getSize() {
133161
return this.size;
134162
}
@@ -138,18 +166,22 @@ class HashTable {
138166
}
139167
}
140168

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);
154186

155187
module.exports = HashTable;

0 commit comments

Comments
 (0)