montagejs / collections

This package contains JavaScript implementations of common data structures with idiomatic interfaces.
http://www.collectionsjs.com
Other
2.09k stars 185 forks source link

A question of collections usage to solve Typescript issue related to tuple key in hashmap #239

Open danielpaz6 opened 4 years ago

danielpaz6 commented 4 years ago

Hi,

So I have a pretty simple example to demonstrate my problem:

export interface Shape {
    name: string;
}

const hashMap = new Map<[Shape, Shape], number>();

const shape1 = {name:"A"};
const shape2 = {name:"B"};

hashMap.set([shape1, shape2], 0);

console.log(hashMap.has([shape1, shape2])); // returns false from some reason

So in this example, I have a Map that uses tuple of Shapes as a key. And it returns false since when using [shape1, shape2] twice, it creates two different arrays in terms of address so the has method probably makes a shallow comparison between them, and as a result, returns false.

I thought maybe I could override has method to fits my needs? to shallow comparison Shape1 and Shape2 instead of the whole array.

Could it be done via collections package?

marchant commented 4 years ago

Yes, dig for the details, but I’m pretty sure it checks if the object has a equals() method and allow what you describe, but the problem you’re going to have is that your tuple is just an array, and adding the equals method on each instance... right, not good. Best would be to have a type of yours instead of just a plain array, that way you have the right structure to consider them equal.