I\'m writing a class
and want the instances to be comparable by <
, >
, ==
.
For <
and ><
You seem to be looking for hash consing, but as you experienced this cannot be implemented efficiently since JavaScript does not (yet) support weak (or soft) references.
No, it is not possible to overwrite any operators, including ==
, in JS. ==
will always compare two objects by reference, there's nothing you can do about it. Your best bet will be creating a compare
method.
First of all keep in mind that ==
is always worse than ===
because of such troubles.
When you use x == y
comparison where both operands are objects then js will compare them as objects. (more here https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Comparison_Operators)
It is easy to test just running
class ComparableObject {
constructor(id) {
this.id = id;
}
valueOf() {
console.log("log", this.id);
return this.id;
}
}
new ComparableObject("12") == new ComparableObject(12);
It will not produce any log but this:
new ComparableObject("12") == new ComparableObject(12).valueOf();
will print:
log 12
log 12
true
There are few solutions for your need:
Number(new ComparableObject("12")) == Number(new ComparableObject(12));
new ComparableObject("12").valueOf() == new ComparableObject(12).valueOf();
GC cannot do something untill cache object will not remove references to instances.