All files / ts/models parent.ts

100% Statements 22/22
100% Branches 9/9
100% Functions 10/10
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  1x               1x         96x       173x 173x       59x 66x 66x         3x 2x   1x 1x 1x   1x       2x 2x 2x 1x   1x 1x         4x          
import { IDestroyable } from "../environment/objectStates.js";
import { IBounds2, Bounds2 } from "./bounds2.js";
 
export interface IParent<T extends IDestroyable> extends IBounds2, IDestroyable {
    readonly children: ReadonlyArray<T>;
    add(...children: T[]): void;
    insert(index: number, ...children: T[]): boolean;
    remove(...children: T[]): void;
}
export abstract class Parent<T extends IDestroyable> extends Bounds2 implements IParent<T> {
 
    private readonly _children: T[];
 
    public get children(): ReadonlyArray<T> {
        return this._children;
    }
 
    public constructor() {
        super();
        this._children = new Array<T>();
    }
 
    public add(...children: T[]): void {
        children.forEach(child => {
            this._children.push(child);
            this.initializeChild(child);
        });
    }
 
    public insert(index: number, ...children: T[]): boolean {
        if (index < 0 || index >= this._children.length || this._children.length < 1)
            return false;
 
        children.forEach(child => {
            this._children.splice(index, 0, child);
            this.initializeChild(child);
        });
        return true;
    }
 
    public remove(...children: T[]): void {
        children.forEach(child => {
            const index = this._children.indexOf(child);
            if (index < 0 || index >= this._children.length)
                return;
 
            this._children.splice(index, 1);
            this.destroyChild(child);
        });
    }
 
    public destroy(): void {
        this._children.forEach(child => this.destroyChild(child));
    }
 
    protected abstract initializeChild(child: T): void;
    protected abstract destroyChild(child: T): void;
}