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");
}