All files / packages/patterns/ecs/src world.ts

100% Statements 22/22
100% Branches 1/1
100% Functions 11/11
100% Lines 21/21

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 733x       3x                   3x         9x 9x       6x       4x       4x   4x   4x       4x       2x 1x     2x       2x 2x       1x 1x             4x 4x     4x      
import { uuid } from "jga-generators-uuid";
 
import { SystemInterface } from "./system";
 
import { Entity } from "./entity";
 
export interface WorldInterface {
    getEntities(): Map<string, Entity>;
    addEntity(entity: Entity): Map<string, Entity>;
    createEntity(): Entity;
    removeEntity(entity: Entity): Map<string, Entity>;
    process(systems: SystemInterface[]): void;
}
 
export class World implements WorldInterface {
    protected entities: Map<string, Entity>;
    protected systems: Set<SystemInterface>;
 
    public constructor() {
        this.entities = new Map<string, Entity>();
        this.systems = new Set<SystemInterface>();
    }
 
    public getEntities(): Map<string, Entity> {
        return this.entities;
    }
 
    public getSystems(): Set<SystemInterface> {
        return this.systems;
    }
 
    public createEntity(): Entity {
        const entity = new Entity(this.generateId());
 
        this.addEntity(entity);
 
        return entity;
    }
 
    public addEntity(entity: Entity): Map<string, Entity> {
        return this.entities.set(entity.getId(), entity);
    }
 
    public removeEntity(entity: Entity): Map<string, Entity> {
        if (this.entities.has(entity.getId())) {
            this.entities.delete(entity.getId());
        }
 
        return this.entities;
    }
 
    public registerSystems(systems: SystemInterface[]): void {
        this.systems.clear();
        systems.forEach((system) => this.systems.add(system));
    }
 
    public process(): void {
        return this.systems.forEach((system): void => {
            system.run(this);
        });
    }
 
    protected generateId(): string {
        let id: string;
        // eslint-disable-next-line no-loops/no-loops
        do {
            id = uuid();
        } while (this.entities.has(id));
 
        return id;
    }
}