Skip to content

Commit

Permalink
fix(equal): account for Weak* objects
Browse files Browse the repository at this point in the history
- `WeakMap` and `WeakSet` cannot be deeply compared (no `size`, `Symbol.iterator`, etc.)
- `WeakRef` can be dereferenced

Refs #949
  • Loading branch information
mfulton26 committed Jun 3, 2021
1 parent 282e0a3 commit e5ceb9d
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 0 deletions.
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

0 comments on commit e5ceb9d

Please sign in to comment.