Skip to content

Commit 10e98a9

Browse files
authored
fix(hash_map): keep entries when trigger resize (TheAlgorithms#130)
1 parent 55a01f2 commit 10e98a9

File tree

2 files changed

+21
-1
lines changed

2 files changed

+21
-1
lines changed

data_structures/map/hash_map.ts

+3-1
Original file line numberDiff line numberDiff line change
@@ -209,10 +209,12 @@ export class HashMap<K, V> implements Map<K, V> {
209209
* Resizes the hash map by doubling the amount of buckets.
210210
*/
211211
private resize(): void {
212+
const entries = this.entries();
213+
212214
this.initializeBuckets(this.buckets.length * 2);
213215
this.size = 0;
214216

215-
for (const entry of this.entries()) {
217+
for (const entry of entries) {
216218
this.set(entry.key, entry.value);
217219
}
218220
}

data_structures/map/test/hash_map.test.ts

+18
Original file line numberDiff line numberDiff line change
@@ -88,4 +88,22 @@ describe("Hash Map", () => {
8888
{ key: "c", value: 3 },
8989
]);
9090
});
91+
92+
it("should keep entries when trigger resize", () => {
93+
hashMap.set('a', 1);
94+
hashMap.set('b', 2);
95+
hashMap.set('c', 3);
96+
hashMap.set('d', 4);
97+
hashMap.set('e', 5);
98+
hashMap.set('f', 6);
99+
hashMap.set('g', 7);
100+
hashMap.set('h', 8);
101+
hashMap.set('i', 9);
102+
hashMap.set('j', 10);
103+
hashMap.set('k', 11);
104+
hashMap.set('l', 12);
105+
hashMap.set('m', 13);
106+
hashMap.set('n', 14);
107+
expect(hashMap.getSize()).toBe(14);
108+
})
91109
});

0 commit comments

Comments
 (0)