I\'m writing a class
and want the instances to be comparable by <
, >
, ==
.
For <
and ><
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.