Skip to content

Commit

Permalink
Added WeakMap and WeakSet comparison handling
Browse files Browse the repository at this point in the history
  • Loading branch information
synapse committed Jun 18, 2024
1 parent 1872167 commit 749daee
Show file tree
Hide file tree
Showing 3 changed files with 48 additions and 1 deletion.
3 changes: 2 additions & 1 deletion doc/api/assert.md
Original file line number Diff line number Diff line change
Expand Up @@ -634,7 +634,8 @@ are also recursively evaluated by the following rules.
* Implementation does not test the [`[[Prototype]]`][prototype-spec] of
objects.
* [`Symbol`][] properties are not compared.
* [`WeakMap`][] and [`WeakSet`][] comparison does not rely on their values.
* [`WeakMap`][] and [`WeakSet`][] comparison does not rely on their values
but only on their instances..
* [`RegExp`][] lastIndex, flags, and source are always compared, even if these
are not enumerable properties.

Expand Down
5 changes: 5 additions & 0 deletions lib/internal/util/comparisons.js
Original file line number Diff line number Diff line change
Expand Up @@ -173,6 +173,11 @@ function innerDeepEqual(val1, val2, strict, memos) {
return false;
}

// Handle WeakMap and WeakSet
if (val1Tag === '[object WeakMap]' || val1Tag === '[object WeakSet]') {
return val1 === val2;
}

if (ArrayIsArray(val1)) {
// Check for sparse arrays and general fast path
if (!ArrayIsArray(val2) || val1.length !== val2.length) {
Expand Down
41 changes: 41 additions & 0 deletions test/parallel/test-assert-deep.js
Original file line number Diff line number Diff line change
Expand Up @@ -1300,3 +1300,44 @@ if (common.hasCrypto) {
}
})().then(common.mustCall());
}

// comparing two identical WeakMap instances
{
const weakMap1 = new WeakMap();
const weakMap2 = weakMap1
assert.deepStrictEqual(weakMap1, weakMap2);
}

// comparing two different WeakMap instances
{
const weakMap1 = new WeakMap();
const objA = {};
weakMap1.set(objA, "ok");

const weakMap2 = new WeakMap();
const objB = {};
weakMap2.set(objB , "ok");

assert.throws(
() => assert.deepStrictEqual(weakMap1, weakMap2),
Error
);
}

// comparing two identical WeakSet instances
{
const weakSet1 = new WeakSet();
const weakSet2 = weakSet1;
assert.deepStrictEqual(weakSet1, weakSet2)
}

// comparing two different WeakSet instances
{
const weakSet1 = new WeakSet();
const weakSet2 = new WeakSet();

assert.throws(
() => assert.deepStrictEqual(weakSet1, weakSet2),
Error
);
}

0 comments on commit 749daee

Please sign in to comment.