Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript Set: any way to override comparison between elements? [duplicate]

A Set handles 2 empty objects as different, e.g.:

let s = new Set([ {} ]);
s.has({}); // false

This is expected, but it would be useful to compare based on their contents instead, as is possible in various other languages.

Is there any way to override the Set's internal comparison operator?

like image 413
Razor Avatar asked Dec 01 '25 16:12

Razor


1 Answers

Is there any way to override the Set's internal comparison operator?

No. Set.prototype.has is defined like this:

23.2.3.7 - Set.prototype.has ( value )

The following steps are taken:

  1. Let S be the this value.
  2. If Type(S) is not Object, throw a TypeError exception.
  3. If S does not have a [[SetData]] internal slot throw a TypeError exception.
  4. Let entries be the List that is the value of S’s [[SetData]] internal slot.
  5. Repeat for each e that is an element of entries,
    1. If e is not empty and SameValueZero(e, value) is true, return true.
  6. Return false.

Therefore, Set must compare using SameValueZero comparison, and you can't change that.

like image 66
Oriol Avatar answered Dec 03 '25 06:12

Oriol



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!