refactor: make getRelatedTo return an iterator

Convert `getRelatedTo` from returning an array to returning an
`IterableIterator`. This improves memory efficiency by yielding
entities lazily instead of allocating a new array on every call.
This commit is contained in:
2026-06-02 06:39:07 +08:00
parent 2469cdc7cb
commit 5d125167cc
3 changed files with 31 additions and 26 deletions
+9 -9
View File
@@ -55,7 +55,7 @@ describe("Relationships", () => {
world.relate(a, ChildOf, parent);
world.relate(b, ChildOf, parent);
const children = world.getRelatedTo(parent, ChildOf);
const children = [...world.getRelatedTo(parent, ChildOf)];
expect(children).toHaveLength(2);
expect(children).toContain(a);
expect(children).toContain(b);
@@ -63,7 +63,7 @@ describe("Relationships", () => {
it("getRelatedTo returns empty when no edges", () => {
const e = world.spawn();
expect(world.getRelatedTo(e, ChildOf)).toEqual([]);
expect([...world.getRelatedTo(e, ChildOf)]).toEqual([]);
});
it("unrelate removes the relationship", () => {
@@ -74,7 +74,7 @@ describe("Relationships", () => {
world.unrelate(child, ChildOf);
expect(world.getRelated(child, ChildOf)).toBeUndefined();
expect(world.getRelatedTo(parent, ChildOf)).toEqual([]);
expect([...world.getRelatedTo(parent, ChildOf)]).toEqual([]);
});
it("unrelate is idempotent", () => {
@@ -89,13 +89,13 @@ describe("Relationships", () => {
world.relate(a, ChildOf, b);
expect(world.getRelated(a, ChildOf)).toBe(b);
expect(world.getRelatedTo(b, ChildOf)).toContain(a);
expect([...world.getRelatedTo(b, ChildOf)]).toContain(a);
world.relate(a, ChildOf, c);
expect(world.getRelated(a, ChildOf)).toBe(c);
// a should no longer point to b
expect(world.getRelatedTo(b, ChildOf)).toEqual([]);
expect(world.getRelatedTo(c, ChildOf)).toContain(a);
expect([...world.getRelatedTo(b, ChildOf)]).toEqual([]);
expect([...world.getRelatedTo(c, ChildOf)]).toContain(a);
});
});
@@ -243,7 +243,7 @@ describe("Destroy cleanup", () => {
world.destroy(child);
expect(world.getRelated(child, ChildOf)).toBeUndefined();
expect(world.getRelatedTo(parent, ChildOf)).toEqual([]);
expect([...world.getRelatedTo(parent, ChildOf)]).toEqual([]);
});
it("removes edges when target is destroyed", () => {
@@ -252,7 +252,7 @@ describe("Destroy cleanup", () => {
world.relate(child, ChildOf, parent);
world.destroy(parent);
expect(world.getRelatedTo(parent, ChildOf)).toEqual([]);
expect([...world.getRelatedTo(parent, ChildOf)]).toEqual([]);
expect(world.getRelated(child, ChildOf)).toBeUndefined();
});
@@ -376,6 +376,6 @@ describe("Dead entity safety", () => {
it("getRelatedTo returns empty for dead entity", () => {
const e = world.spawn();
world.destroy(e);
expect(world.getRelatedTo(e, ChildOf)).toEqual([]);
expect([...world.getRelatedTo(e, ChildOf)]).toEqual([]);
});
});