mirror of
https://github.com/discordjs/discord.js.git
synced 2026-03-09 08:03:30 +01:00
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:
@@ -207,6 +207,23 @@ describe('equals() tests', () => {
|
|||||||
const coll3 = createCollectionFrom(['a', 2], ['b', 3], ['c', 3]);
|
const coll3 = createCollectionFrom(['a', 2], ['b', 3], ['c', 3]);
|
||||||
expect(coll2.equals(coll3)).toBeFalsy();
|
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', () => {
|
describe('every() tests', () => {
|
||||||
|
|||||||
@@ -822,7 +822,11 @@ export class Collection<Key, Value> extends Map<Key, Value> {
|
|||||||
if (this === collection) return true;
|
if (this === collection) return true;
|
||||||
if (this.size !== collection.size) return false;
|
if (this.size !== collection.size) return false;
|
||||||
for (const [key, value] of this) {
|
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;
|
return false;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user