Tweaking ES2015 Map to support desired behavior

Viewed 57

I am playing around with ES2015 Maps and I am discovering that it is a great feature. However, I now have a use case that I cannot quite figure out whether or not can work out with Maps.

Consider my class

class A {
     constructor(public a:number) {}
     public equals(obj: A): boolean {
         return this.a === obj.a;
     }
 }

As far as I understand will ES2015 Maps use the === equality operator (with some exceptions). Thus I wonder if it is possible to kind of overwrite the equality and force it to use the A object's equals(...) method if instanceof?

Ultimately this is what I would like to achieve:

var map = new Map();
map.set(new A(8), 7)
map.get(new A(8))      // return 7, not undefined

Do you think I have to create my own Map class to implement this behavior that checks if both objects are instances of A and then call the equals(...) method?

1 Answers
Related