Skip to content Skip to sidebar Skip to footer

How Do I Make A Class's Instances Comparable And Garbage Collectable At The Same Time?

I'm writing a class and want the instances to be comparable by <, >, ==. For < and >, valueOf works fine. == is different, however, but I want to have that as well. I c

Solution 1:

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.

Solution 2:

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

classComparableObject {
  constructor(id) {
    this.id = id;
  }

  valueOf() {
    console.log("log", this.id);
    returnthis.id;
  }
}

newComparableObject("12") == newComparableObject(12);

It will not produce any log but this:

newComparableObject("12") == newComparableObject(12).valueOf();

will print:

log 12
log 12
true

There are few solutions for your need:

Number(newComparableObject("12")) == Number(newComparableObject(12));
newComparableObject("12").valueOf() == newComparableObject(12).valueOf();

GC cannot do something untill cache object will not remove references to instances.

Post a Comment for "How Do I Make A Class's Instances Comparable And Garbage Collectable At The Same Time?"