Skip to content

Commit

Permalink
can now map and foreach with outh new entities input
Browse files Browse the repository at this point in the history
  • Loading branch information
Yoieh committed Nov 28, 2021
1 parent 2bdaa4b commit 266e07f
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 6 deletions.
9 changes: 3 additions & 6 deletions src/ecs/Query.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,31 +10,28 @@ export class Query {
return this._filter;
}

private readonly _entities: IEntity[];

private readonly _entityManager: EntityManager;

constructor(filter: QueryFilter, entityManager: EntityManager = EntityManager.instance) {
this._filter = filter;
this._entityManager = entityManager;
this._entities = entityManager.entities;
}

public find(entities: IEntity[]): IEntity | undefined {
return entities.find(this._filter);
}

public filter(entities: IEntity[] = this._entities): IEntity[] {
public filter(entities: IEntity[] = this._entityManager.entities): IEntity[] {
return entities.filter(this._filter);
}

public map(callback: (entity: IEntity) => IEntity, entities: IEntity[]): IEntity[] {
public map(callback: (entity: IEntity) => IEntity, entities: IEntity[] = this.filter()): IEntity[] {
return entities.map((entity) => {
return callback(entity);
});
}

public foreach(callback: (entity: IEntity) => void, entities: IEntity[]): void {
public foreach(callback: (entity: IEntity) => void, entities: IEntity[] = this.filter()): void {
entities.forEach((entity) => {
if (this._filter(entity)) {
callback(entity);
Expand Down
19 changes: 19 additions & 0 deletions tests/ecs/Query.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -206,6 +206,25 @@ describe('>>> Query', () => {
expect(afterEntities).toBeDefined();
expect(afterEntities.length).toBe(beforeEntities.length - updateEntities.length);
});

it('should map to add component C3 to all entities missing C3 component without filter', () => {
const hasC3Query = new Query((entity: IEntity) => entity.has(C3), entityManager);
const beforeEntities = hasC3Query.map((entity: IEntity) => entity);

expect(beforeEntities).toBeDefined();
expect(beforeEntities.length).toBe(1);

const updateQuery = new Query((entity: IEntity) => entity.hasNone(C3), entityManager);
const updateEntities = updateQuery.map((entity: IEntity) => entity.add(new C3()));

expect(updateEntities).toBeDefined();
expect(updateEntities.length).toBe(2);

const afterEntities = hasC3Query.map((entity: IEntity) => entity);

expect(afterEntities).toBeDefined();
expect(afterEntities.length).toBe(beforeEntities.length + updateEntities.length);
});
});

describe('>>> Query foreach', () => {
Expand Down

0 comments on commit 266e07f

Please sign in to comment.