I was interested in building a 3D engine from scratch using the ECS (Entity Component System) pattern, because of its applications to synchronizations problems. [Click here](https://cdn.theolouvel.com/459630d1-29d9-44ac-aca8-afcf6e2516de.webm) if you want a peek at the result of this proof of concept. This pattern involves maintaining a list of all the entities that have a component, for each component. Systems, on the other hand, rely on the ability to retrieve efficiently entities that have certain components implemented so that you can query "all the spheres that have both a position and a velocity", for instance. Since order is arbitrary in those lists of entities, and since by "entity" we only really mean strings representing ids, `Set` are both the idiomatic and mathematically correct way to represent them. It follows that in order to retrieve entities that have both the `Velocity` and `Position` component, you need to intersect those two sets (find the entities that are in both lists). I first wrote my own implementation of set intersection before realizing the `Set.prototype.intersection` method had been available since 2024.[^1] Because this is fairly recent, you have to be mindful of backward compatibility. Perhaps some polyfills are available for that purpose. Given two sets, $A$ and $B$, this returns ![](https://cdn.theolouvel.com/e89441a9-026f-4fa7-a849-efd3e82bc6dc.webp) ```js const A = new Set([1, 2, 3]); const B = new Set([2, 3, 4]); const C = A.intersection(B); // Set {2, 3} ``` If you want to intersect more than two sets, ```js const A = new Set([1, 2, 3]); const B = new Set([2, 3, 4]); const C = new Set([0, 2, 1]); const sets = [A,B,C]; // Sort to minimize lookups sets.sort((a, b) => a.size - b.size); sets.reduce((acc, s) => acc.intersection(s), sets[0]); // Set {2} ``` [^1]: See the [MDN doc](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set/intersection)