How do I check for equality and sameness on class instances with respect to usage of ES6's Set collection?
<p>I am trying to use ES6 from TypeScript via <a href="https://github.com/Microsoft/TypeScript/blob/master/lib/lib.es6.d.ts" rel="nofollow noreferrer">lib.es6.d.ts</a>. I need to understand how to <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Equality_comparisons_and_sameness" rel="nofollow noreferrer">enforce equality comparison and sameness</a> for an object for use in a <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set" rel="nofollow noreferrer"><code>Set&lt;T&gt;</code></a>. For example, the object looks like the following. </p>

<pre><code>class Product {
 metadata: Map&lt;String, String&gt;

 constructor(id: number) { 
  metadata = new Map&lt;String, String&gt;();
 }

 public addMetadata(key: String, val: String): Product {
  this.metadata.set(key, val);
  return this;
 }
}
</code></pre>

<p>Note that <code>id</code> field value in <code>Product</code> is what determines its uniqueness. If two Product instances have the same id, they are considered the same in my application, even if the <code>metadata</code> differs. In general, I only want only a subset of the fields to be used as a part of testing for equality and sameness.</p>

<p>In Java, we override the <code>equals</code> method to control and test for sameness. In JavaScript, what do we need to do to determine sameness? </p>

<p>The <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set" rel="nofollow noreferrer">link on MDN</a> states the following:</p>

<blockquote>
  <p>Because each value in the Set has to be unique, the value equality will be checked. </p>
</blockquote>

<p>I assume by value equality they mean <code>===</code>? Again, <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Equality_comparisons_and_sameness" rel="nofollow noreferrer">MDN shows 4 equality algorithms</a> in ES2015 alone.</p>

<p>Basically, in my class above, I want to do something like the following.</p>

<pre><code>let p1 = new Product(1);
let p2 = new Product(2);
let p3 = new Product(1); //duplicate of p1 by id

p1.addMetadata('k1','v1').addMetadata('k2','v2');
p2.addMetadata('k1','v1');

let mySet = new Set&lt;Product&gt;();
mySet.add(p1);
mySet.add(p2);
mySet.add(p3);

assertEquals(2, mySet.size); //some assertion method
</code></pre>