Skip to content

fix(hash_map): keep entries when trigger resize #130

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Jun 16, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 3 additions & 1 deletion data_structures/map/hash_map.ts
Original file line number Diff line number Diff line change
Expand Up @@ -209,10 +209,12 @@ export class HashMap<K, V> implements Map<K, V> {
* 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);
}
}
Expand Down
18 changes: 18 additions & 0 deletions data_structures/map/test/hash_map.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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);
})
});