diff --git a/data_structures/map/hash_map.ts b/data_structures/map/hash_map.ts index e4ad04b6..3a57d759 100644 --- a/data_structures/map/hash_map.ts +++ b/data_structures/map/hash_map.ts @@ -209,10 +209,12 @@ export class HashMap implements Map { * Resizes the hash map by doubling the amount of buckets. */ private resize(): void { + const entries = this.entries(); + this.initializeBuckets(this.buckets.length * 2); this.size = 0; - for (const entry of this.entries()) { + for (const entry of entries) { this.set(entry.key, entry.value); } } diff --git a/data_structures/map/test/hash_map.test.ts b/data_structures/map/test/hash_map.test.ts index ef561d97..16640e97 100644 --- a/data_structures/map/test/hash_map.test.ts +++ b/data_structures/map/test/hash_map.test.ts @@ -88,4 +88,22 @@ describe("Hash Map", () => { { key: "c", value: 3 }, ]); }); + + it("should keep entries when trigger resize", () => { + hashMap.set('a', 1); + hashMap.set('b', 2); + hashMap.set('c', 3); + hashMap.set('d', 4); + hashMap.set('e', 5); + hashMap.set('f', 6); + hashMap.set('g', 7); + hashMap.set('h', 8); + hashMap.set('i', 9); + hashMap.set('j', 10); + hashMap.set('k', 11); + hashMap.set('l', 12); + hashMap.set('m', 13); + hashMap.set('n', 14); + expect(hashMap.getSize()).toBe(14); + }) });