Code Review Stack Exchange is a question and answer site for peer programmer code reviews. It's 100% free, no registration required.

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

this.collisions is a 2D array containing a list of collisions that, when bodies collide, they should be added to it. Here's an example:

[[A, C], [B, D]]

Means that A and C are colliding, as well as B and D.

But eventually A will enter in contact with B, so both arrays should merge into a single item on the outer array:

[[A, C, B, D]]

Here's how I achieved this, in JavaScript ES6:

addCollision (bodyA, bodyB) {
    if (bodyA.collision === null && bodyB.collision === null) {
        bodyA.collision = this.collisions.length;
        bodyB.collision = bodyA.collision;
        this.collisions.push([bodyA, bodyB]);
    } else if (bodyA.collision !== null && bodyB.collision === null) {
        bodyB.collision = bodyA.collision;
        this.collisions[bodyA.collision].push(bodyB);
    } else if (bodyB.collision !== null && bodyA.collision === null) {
        bodyA.collision = bodyB.collision;
        this.collisions[bodyB.collision].push(bodyA);
    } else if (bodyA.collision !== bodyB.collision) {
        let bodyBCollisionIndex = bodyB.collision;
        for (let i = 0; i < this.collisions[bodyBCollisionIndex].length; ++i){
            let bodyC = this.collisions[bodyBCollisionIndex][i];
            bodyC.collision = bodyA.collision;
            this.collisions[bodyA.collision].push(bodyC);
        }
        this.collisions[bodyB.collision].length = 0;
    }
}

bodyX.collision is set when the body first collides or when this merge is made, so I don't need to use the more expensive indexOf to find its index every time I want it.

Note that order isn't important. Empty nested arrays can (and should) be removed if the performance from looping through this.collisions is increased and no performance is loss during the removal.

How can I improve this code, in order to make it cleaner and faster? Also, is there a more ES6-ish approach to what I am currently doing?

share|improve this question

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Browse other questions tagged or ask your own question.