Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Filter array and cast array to different type of array

Tags:

typescript

I'm building a game with GameObjects. In my game i have separated GameObjects from CollidableObject. All objects (GameObjects and CollidableGameObjects) are pushed to one single array called gameObjects.

When it comes to collision detection i wish to filter the gameObjects array so i can loop over only objects of type CollidableObject. I created the following code for this:

let temp : any = this.gameObjects.filter(g => g instanceof CollidableObject);

//optional
let collidables : Array<CollidableObject> = temp;

for (let obj1 of collidables) {
    for (let obj2 of collidables){
        if (obj1 != obj2) {
            if(obj1.hasCollision(obj2)) {        
                obj1.onCollision(obj2);
                this.gameOver();
            } 
        }
    }
}

Question 1: Why is it not possible to directly filter to an array of CollidableObject?

Question 2: Is there an easier way to filter the array on a certain type?

like image 658
Bob Pikaar Avatar asked Jun 06 '17 12:06

Bob Pikaar


1 Answers

You can do this:

let temp = this.gameObjects.filter(g => g instanceof CollidableObject) as CollidableObject[];

Or add a signature to the array interface:

interface Array<T> {
    filter<S>(callbackfn: (this: void, value: T, index: number, array: T[]) => boolean): S[];
}

And then:

let temp = this.gameObjects.filter<CollidableObject>(g => g instanceof CollidableObject);

If you're using a module system (that is you are importing/exporting) then you need to augment the global module:

declare global {
    interface Array<T> {
        filter<S>(callbackfn: (this: void, value: T, index: number, array: T[]) => boolean): S[];
    }
}
like image 71
Nitzan Tomer Avatar answered Sep 28 '22 05:09

Nitzan Tomer