danielmathias
danielmathias

Reputation: 11

How can I iterate over two arrays that share a common property?

I've been working on a very slim Entity Component System in javascript using Pixi.js on the frontend, and I had a question for you folks A common pattern is the iterators that you use in systems, for example in Unity you can do:

    [ComponentType1, ComponentType2], 
    (c1: ComponentType1, c2: ComponentType2) => {
         // run ops on the components
     })

How would you architect that forEach function under the hood, given that you have an array of entities and two arrays containing those component types, needing to call a function and pass in the two components as arguments? Essentially, what is the most optimized way to iterate over entities that have both types of components?

Easy way seems to be iterator over the list of entities and check their component types, but i'm wondering if theres a better way. That approach would look something like this:

function forEach<T, K>(components: [c1: T, c2: K], callback: (c1: T, c2: K)=> void) {
    entities.forEach((entity) => { 

        if (entity.hasComponent(c1) && entity.hasComponent(c2)) {

            callback(entity.getComponent(c1), entity.getComponent(c2)

        }
}

Upvotes: 0

Views: 84

Answers (0)

Related Questions