Set Comparability for Objects in ECMA6 JS

63 views Asked by At

I've been using a set to store and retrieve simple objects which represent coordinates.

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

I am generating these points multiple times, so that I have easy coordinate pairs to pass around, but I wish to be able to store them in such a way that I do not store duplicate coordinates.

The ECMA 6 Set object relies on references to test object equality, so I am wondering if there is a way to supply this set with a comparable function so that I may allow it to test equality for new objects with the same fields. Otherwise, is there something else I can do to avoid re-implementing this data structure?

1

There are 1 answers

3
Cymen On BEST ANSWER

Why not add an isEqual(otherPoint)? It might look something like:

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

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

Then you can make instances of HexPoint with:

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

A similar Q&A points out no native option exists yet.