Skip to content
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

Consolidates asserts#equal branches for keyed collections (Map/Set) and supports deep equality of Map keys #3258

Merged
merged 13 commits into from
Nov 4, 2019
Merged
Prev Previous commit
Next Next commit
Supports deep equality of Map and Set keys
  • Loading branch information
jamesseanwright committed Nov 3, 2019
commit a67eb304cdc292f4910b10ade74ed1339cd7a8e3
18 changes: 12 additions & 6 deletions std/testing/asserts.ts
Original file line number Diff line number Diff line change
Expand Up @@ -69,8 +69,8 @@ function buildMessage(diffResult: ReadonlyArray<DiffResult<string>>): string[] {

function isKeyedCollection(
x: unknown
): x is Map<unknown, unknown> | Set<unknown> {
return x instanceof Map || x instanceof Set;
): x is Set<unknown> {
return [Symbol.iterator, 'size'].every(k => k in (x as Set<unknown>));
}

export function equal(c: unknown, d: unknown): boolean {
Expand Down Expand Up @@ -101,13 +101,19 @@ export function equal(c: unknown, d: unknown): boolean {
return false;
}

for (const [key, value] of a.entries()) {
if (!b.has(key) || !compare(value, "get" in b ? b.get(key) : key)) {
return false;
let matchedEntries = 0;

for (const [aKey, aValue] of a.entries()) {
for (const [bKey, bValue] of b.entries()) {
/* Given that keys can be references, we need
* to ensure that they are also deeply equal */
if (compare(aKey, bKey) && compare(aValue, bValue)) {
matchedEntries++;
}
}
}

return true;
return matchedEntries === a.size;
}
const merged = { ...a, ...b };
for (const key in merged) {
Expand Down
22 changes: 22 additions & 0 deletions std/testing/asserts_test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,7 @@ test(function testingEqual(): void {
assert(equal(new Set([1]), new Set([1])));
assert(!equal(new Set([1]), new Set([2])));
assert(equal(new Set([1, 2, 3]), new Set([3, 2, 1])));
assert(equal(new Set([1, new Set([2, 3])]), new Set([new Set([3, 2]), 1])));
assert(!equal(new Set([1, 2]), new Set([3, 2, 1])));
assert(!equal(new Set([1, 2, 3]), new Set([4, 5, 6])));
assert(equal(new Set("denosaurus"), new Set("denosaurussss")));
Expand Down Expand Up @@ -84,6 +85,27 @@ test(function testingEqual(): void {
)
);

assert(
equal(
new Map([[{x: 1}, true]]),
new Map([[{x: 1}, true]])
)
);

assert(
!equal(
new Map([[{x: 1}, true]]),
new Map([[{x: 1}, false]])
)
);

assert(
!equal(
new Map([[{x: 1}, true]]),
new Map([[{x: 2}, false]])
)
);

assert(equal([1, 2, 3], [1, 2, 3]));
assert(equal([1, [2, 3]], [1, [2, 3]]));
assert(!equal([1, 2, 3, 4], [1, 2, 3]));
Expand Down