How do I make a class's instances comparable and garbage collectable at the same time?

前端 未结 2 1035
一生所求
一生所求 2021-01-21 02:55

I\'m writing a class and want the instances to be comparable by <, >, ==.

For < and ><

相关标签:
2条回答
  • 2021-01-21 03:16

    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.

    0 讨论(0)
  • 2021-01-21 03:27

    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.

    0 讨论(0)
提交回复
热议问题