在 ECMA6 JS 中设置对象的可比性

Set Comparability for Objects in ECMA6 JS

我一直在使用集合来存储和检索表示坐标的简单对象。

// Creates a point in hex coordinates
  function hexPoint(q, r) {
    this.q = q;
    this.r = r;
  }

我多次生成这些点,这样我就可以轻松传递坐标对,但我希望能够以不存储重复坐标的方式存储它们。

ECMA 6 Set 对象依赖于引用来测试对象相等性,所以我想知道是否有办法为这个集合提供可比较的函数,以便我可以允许它测试具有相同功能的新对象的相等性领域。否则,我还能做些什么来避免重新实现这个数据结构吗?

为什么不添加一个isEqual(otherPoint)?它可能看起来像:

function HexPoint(q, r) {
  this.q = q;
  this.r = r;
}

HexPoint.prototype.isEqual = function(otherPoint) {
  return this.q === otherPoint.q && this.r === otherPoint.r;
}

然后你可以创建 HexPoint 的实例:

var point = new HexPoint(...);
if (point.isEqual(someOtherPoint)) {
  ...
}

A similar Q&A 指出还没有本机选项存在。