1

Is there a way to test if two (or more) WeakSets are equal? So, I want this code to print out true

var a = new WeakSet();
var b = new WeakSet();
a.add([3]);
b.add([3]);
console.log(isEqual(a, b)); // -> true
  • 3
    `[3] === [3]` is `false`, which is just the first problem here. The second being that you add these as literals, so there are no other references to the arrays, which makes them eligible for garbage collection. In a way `a` and `b` should therefore both be equal because they should both be empty but it might differ based on when GC runs. – VLAZ May 25 '21 at 08:59
  • Would like to know why you want to compare 2 WeakSet? or is that your requirement is to compare 2 arrays? – Vivek Bani May 25 '21 at 09:04
  • I'm trying to compare 2 WeakSets because I'm currently working on 'isEqual' function. –  May 25 '21 at 09:23

1 Answers1

1

Simple answer - you can't. WeakSets are not enumerable so there is no way to test the equality of values in a WeakSet.

Currently your only option is to use Array here.
Check out this answer.

Also see this proposal if you want to use Set instead.

Though I doubt that your use case requires that kind of memory management, you may also consider WeakReferences as part of your solution.

As a side note, WeakSets have very few actual use-cases, so you probably should not settle for them.

Heniker
  • 589
  • 6
  • 13