0

Well consider I have some "complex" data stored inside a set. Now instead of a reference-equal comparison when checking for containment I wish to perform a (custom) value comparison. -- As done by the function equals below.

I understand javascript doesn't have operator overloading, but what then is the idiomatic way to do this? (Other than writing my own contains function that simply loops over all elements and thus has an O(n) algorithmic efficiency).

I kind of expect having to give both a custom hash function as well as a custom comparison function. Are there magic methods like python's __equals__ and __hash__ I need to overwrite?

class data {
  public data: [number, string]; //would be hidden later and accessed by getters for left and right
  constructor (left: number, right: string) {
    this.data=[left, right];
  }
  public equals(rhs: data): boolean {
    return this.data[0] === rhs.data[0] && this.data[1] === rhs.data[1];
  }
}
let theSet = new Set();
let n = 0;
let s = "hello world";
let dat1 = new data(n, s);
theSet.add(dat1);
let dat2 = new data(n, s);
if (theSet.has(dat2)) {
  alert("contains");
} else {
  alert("doesn't contain");
}
paul23
  • 7,226
  • 9
  • 44
  • 108
  • @Axnyff indeed a duplicate - but the answer isn't an answer. It describes the problem (like I did) but doesn't give an answer. - The "suggestion" even states it's not good since it doesn't adhere to the O(1) speed. – paul23 Nov 07 '17 at 14:44
  • It's not clear what you're asking here. If you want to compare two Set instances and determine whether they contain the same elements, you're going to have to perform a linear comparison one way or another. – Pointy Nov 07 '17 at 14:50
  • Also two separate instances of your `data` class will never be considered equal by ordinary JavaScript comparison rules, and there's no such thing as Java `.equals()` to override. – Pointy Nov 07 '17 at 14:51
  • As the linked question's answer clearly says, there is no way to "customize" the way a JavaScript Set works. – Pointy Nov 07 '17 at 14:51
  • Are you really looking for a general solution or just something to hold your particular `data` class? – jcalz Nov 07 '17 at 15:07

0 Answers0