Coming from a different language (where such thing was trivial), I am struggling to express a list of pairs:
- Each pair consists of two primitives (strings, or numbers)
- Each value can repeat multiple times, but a combination must be unique:
a, k
a, m
b, m
b, n
The 2 features I need are:
- Be able to add a pair, knowing that if a pair repeats, it won’t be added (e.g. if I try to add
a, k
to the above list, the second instance won’t be added - I should be able to check if the pair is in the list. E.g. if I check
b, n
it would returntrue
, andb, p
would return false.
What’s the suitable implementation in typescript?
Originally I was thinking of Set<[string, string]>
:
const a = new Set<[string, string]>();
a.add(['a', 'k']);
a.add(['a', 'm']);
a.add(['b', 'm']);
a.add(['b', 'n']);
...
But of course the issue is that it compares object, so a.has(['a', 'b'])
returns false
.
So what are the other options?
2
Answers
How about creating your own utility for this?
When using it with your example:
JS
Set
checks element equality usingObject.is
. Thus, for arrays it compares if it is the same instance or the array.See Set in MDN
See Equality comparisons and sameness
I would consider a class holding your arrays in stringified form:
See also: Storing arrays in ES6 Set and accessing them by value