Skip to content

Commit 1d1c686

Browse files
committed
Avoid notifying non-existent members on Map.clear()
1 parent 4de408a commit 1d1c686

File tree

3 files changed

+54
-7
lines changed

3 files changed

+54
-7
lines changed

.changeset/red-islands-tickle.md

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
---
2+
"@solid-primitives/map": minor
3+
---
4+
5+
Avoid notifying non-existent members on Map.clear()

packages/map/src/index.ts

Lines changed: 10 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -120,14 +120,17 @@ export class ReactiveMap<K, V> extends Map<K, V> {
120120
}
121121

122122
clear(): void {
123-
if (super.size) {
124-
super.clear();
123+
if (super.size === 0) return;
124+
batch(() => {
125+
this.#keyTriggers.dirty($OBJECT);
126+
this.#valueTriggers.dirty($OBJECT);
127+
for (const key of super.keys()) {
128+
this.#keyTriggers.dirty(key);
129+
this.#valueTriggers.dirty(key);
130+
}
125131

126-
batch(() => {
127-
this.#keyTriggers.dirtyAll();
128-
this.#valueTriggers.dirtyAll();
129-
});
130-
}
132+
super.clear();
133+
});
131134
}
132135
}
133136

packages/map/test/index.test.ts

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -378,6 +378,45 @@ describe("ReactiveMap", () => {
378378

379379
dispose();
380380
});
381+
test(".clear() notifies only listeners of existing members", () =>
382+
createRoot(dispose => {
383+
const map = new ReactiveMap([
384+
[1, "a"],
385+
[2, "b"],
386+
[3, "c"],
387+
]);
388+
389+
const existingKey = vi.fn();
390+
createComputed(() => existingKey(map.has(2)));
391+
392+
const existingValue = vi.fn();
393+
createComputed(() => existingValue(map.get(2)));
394+
395+
const nonexistingKey = vi.fn();
396+
createComputed(() => nonexistingKey(map.has(4)));
397+
398+
const nonexistingValue = vi.fn();
399+
createComputed(() => nonexistingValue(map.get(4)));
400+
401+
expect(existingKey).toHaveBeenNthCalledWith(1, true);
402+
expect(existingValue).toHaveBeenNthCalledWith(1, "b");
403+
404+
expect(nonexistingKey).toHaveBeenNthCalledWith(1, false);
405+
expect(nonexistingValue).toHaveBeenNthCalledWith(1, undefined);
406+
407+
map.clear();
408+
409+
expect(existingKey).toHaveBeenCalledTimes(2);
410+
expect(existingKey).toHaveBeenNthCalledWith(2, false);
411+
412+
expect(existingValue).toHaveBeenCalledTimes(2);
413+
expect(existingValue).toHaveBeenNthCalledWith(2, undefined);
414+
415+
expect(nonexistingKey).toHaveBeenCalledTimes(1);
416+
expect(nonexistingValue).toHaveBeenCalledTimes(1);
417+
418+
dispose();
419+
}));
381420
});
382421

383422
describe("ReactiveWeakMap", () => {

0 commit comments

Comments
 (0)