I am working with TypeScript and aiming to create a collection of unique objects, each with distinct properties. The combinations of these properties within the collection must be one-of-a-kind.
For example, the following combinations would be considered valid:
[
[ 1, 2 ],
[ 2, 1 ],
]
However, attempting to add a duplicate combination such as [ 1, 2 ]
would result in a "key already exists" error.
It's worth noting that my query assumes the presence of 3 keys representing the "composite key," but I am open to more flexible solutions if they exist.
In an attempt to address this challenge, I developed my own JavaScript-based "map-like" structure as a demonstration:
class MyCollection {
constructor() {
this.items = [];
}
add(firstTupleItem, secondTupleItem, thirdTupleItem) {
if (this.has(firstTupleItem, secondTupleItem, thirdTupleItem)) {
console.log(`ERR: Combination of [${firstTupleItem}, ${secondTupleItem}, ${thirdTupleItem}] already exists!`);
return;
}
console.log(`Added combination of [${firstTupleItem}, ${secondTupleItem}, ${thirdTupleItem}]`);
this.items.push([firstTupleItem, secondTupleItem, thirdTupleItem]);
}
has(firstTupleItem, secondTupleItem, thirdTupleItem) {
return this.items.some(item =>
item[0] === firstTupleItem &&
item[1] === secondTupleItem &&
item[2] === thirdTupleItem);
}
}
const myCollection = new MyCollection();
/* passes as expected */
myCollection.add(1, 2, 3);
myCollection.add(2, 1, 3);
myCollection.add(3, 1, 2);
myCollection.add(1, 3, 2);
/* fails as expected */
myCollection.add(1, 2, 3);
console.log(myCollection.items);
While using a map could potentially offer improved efficiency, there may be concerns regarding the utilization of the value side. As an alternative concept, consider the following:
class MyCustomMap extends Map<[number, number, number], [number, number, number]> {
addItem(item: [number, number, number]) {
super.set(item, item);
}
}
Is it necessary for me to create such a collection structure from scratch, or are there alternative, more efficient solutions available? (particularly within the context of TypeScript)