0

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?

  • plain objects don't have repeats, and you can use your numbers as keys, sticking q+r together to make a "unique" key that you can look for in hexPoint() before returning a new object. – dandavis Jun 23 '15 at 19:41

1 Answers1

0

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.

Community
  • 1
  • 1
Cymen
  • 14,079
  • 4
  • 52
  • 72
  • Will the Set be able to use the isEqual function to perform its equality checks? As I understand it, the implementation of set only checks the reference and does not perform any other checks. I want the set to be able to maintain its own uniqueness without me having to check for it. – Michael Von Hippel Jun 23 '15 at 19:36
  • @MichaelVonHippel I think you have to build a say a UniqueSet class if you want that. It would check on `add` if the `Object` was already present. If using `HexPoint`, you'd probably want to add an `isEqual` like above and use it. – Cymen Jun 23 '15 at 19:45
  • Unfortunately, doing that check seems like needless complexity to add(since I would have to iterate over all existing elements anyway.) I guess the alternative is to use a factory for all hexpoints or simply make my own set that implements hashing. – Michael Von Hippel Jun 23 '15 at 20:13