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

fix(equal): account for Weak* objects #951

Merged
merged 1 commit into from
Jun 7, 2021
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
12 changes: 12 additions & 0 deletions testing/asserts.ts
Original file line number Diff line number Diff line change
Expand Up @@ -122,6 +122,14 @@ export function equal(c: unknown, d: unknown): boolean {
return true;
}
if (a && typeof a === "object" && b && typeof b === "object") {
if (a instanceof WeakMap || b instanceof WeakMap) {
if (!(a instanceof WeakMap && b instanceof WeakMap)) return false;
throw new TypeError("cannot compare WeakMap instances");
}
if (a instanceof WeakSet || b instanceof WeakSet) {
if (!(a instanceof WeakSet && b instanceof WeakSet)) return false;
throw new TypeError("cannot compare WeakSet instances");
}
if (seen.get(a) === b) {
return true;
}
Expand Down Expand Up @@ -166,6 +174,10 @@ export function equal(c: unknown, d: unknown): boolean {
}
}
seen.set(a, b);
if (a instanceof WeakRef || b instanceof WeakRef) {
if (!(a instanceof WeakRef && b instanceof WeakRef)) return false;
return compare(a.deref(), b.deref());
}
return true;
}
return false;
Expand Down
26 changes: 26 additions & 0 deletions testing/asserts_test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -153,6 +153,32 @@ Deno.test("testingEqual", function (): void {
assert(
!equal({ a: undefined, b: undefined }, { a: undefined }),
);
assertThrows(() => equal(new WeakMap(), new WeakMap()));
assertThrows(() => equal(new WeakSet(), new WeakSet()));
assert(!equal(new WeakMap(), new WeakSet()));
assert(
equal(new WeakRef({ hello: "world" }), new WeakRef({ hello: "world" })),
);
assert(
!equal(new WeakRef({ world: "hello" }), new WeakRef({ hello: "world" })),
);
assert(!equal({ hello: "world" }, new WeakRef({ hello: "world" })));
assert(
equal(
new WeakRef({ hello: "world" }),
// deno-lint-ignore ban-types
new (class<T extends object> extends WeakRef<T> {})({ hello: "world" }),
),
);
assert(
!equal(
new WeakRef({ hello: "world" }),
// deno-lint-ignore ban-types
new (class<T extends object> extends WeakRef<T> {
foo = "bar";
})({ hello: "world" }),
),
);
});

Deno.test("testingNotEquals", function (): void {
Expand Down