perf: Optimize Collection.equals() to reduce redundant map lookups (#11344)

* Initial plan

* Optimize Collection.equals() to avoid redundant map lookups

Co-authored-by: iCrawl <20760160+iCrawl@users.noreply.github.com>

* Add explanatory comment for equals() undefined check optimization

Co-authored-by: iCrawl <20760160+iCrawl@users.noreply.github.com>

---------

Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com>
Co-authored-by: iCrawl <20760160+iCrawl@users.noreply.github.com>
Co-authored-by: Almeida <github@almeidx.dev>
Co-authored-by: kodiakhq[bot] <49736102+kodiakhq[bot]@users.noreply.github.com>
This commit is contained in:
Copilot
2025-12-09 21:22:14 +00:00
committed by GitHub
parent 6a129bc054
commit 548d75258b
2 changed files with 22 additions and 1 deletions

View File

@@ -207,6 +207,23 @@ describe('equals() tests', () => {
const coll3 = createCollectionFrom(['a', 2], ['b', 3], ['c', 3]);
expect(coll2.equals(coll3)).toBeFalsy();
});
test('collections with undefined values should be compared correctly', () => {
const collWithUndefined1 = new Collection<string, number | undefined>([
['a', 1],
['b', undefined],
]);
const collWithUndefined2 = new Collection<string, number | undefined>([
['a', 1],
['b', undefined],
]);
const collWithDifferentKeys = new Collection<string, number | undefined>([
['a', 1],
['c', undefined],
]);
expect(collWithUndefined1.equals(collWithUndefined2)).toBeTruthy();
expect(collWithUndefined1.equals(collWithDifferentKeys)).toBeFalsy();
});
});
describe('every() tests', () => {

View File

@@ -822,7 +822,11 @@ export class Collection<Key, Value> extends Map<Key, Value> {
if (this === collection) return true;
if (this.size !== collection.size) return false;
for (const [key, value] of this) {
if (!collection.has(key) || value !== collection.get(key)) {
const otherValue = collection.get(key);
// If values differ, collections aren't equal.
// For undefined values, we must also verify the key exists in the other collection,
// since get() returns undefined for both missing keys and keys with undefined values.
if (otherValue !== value || (otherValue === undefined && !collection.has(key))) {
return false;
}
}