javascripttypescriptnon-repetitive

Repetitive value assignment with computation


I have some TS code that I'm not happy with. I'im doing three times the same thing. How could this be cleaner?

A position object has an x, y and z axis that can be set with position.x = ... or give it all the values with position.set(x,y,z).

Could I use a sort of map function that goes over all the values and assigns a new value based on some computation.

private moveTowardsCamera(camera: THREE.Camera) {
        this.children.forEach((child: Asteroid) => {
            child.position.set(
                child.position.x += (camera.position.x - child.position.x) * this.speed,
                child.position.y += (camera.position.y - child.position.y) * this.speed,
                child.position.z += (camera.position.z - child.position.z) * this.speed  
            );
            child.rotation.set(
                child.rotation.x += this.rotationIncrement,
                child.rotation.y += this.rotationIncrement,
                child.rotation.z += this.rotationIncrement
            );
        });
    }

Solution

  • You can iterate over an array of ['x', 'y', 'z'], map it, and spread it into the different .set calls:

    // make sure to use `as const` here so the type doesn't get widened to Array<string>
    const dims = ['x', 'y', 'z'] as const;
    private moveTowardsCamera(camera: THREE.Camera) {
        this.children.forEach((child: Asteroid) => {
            child.position.set(
                ...(dims.map(dim => 
                    child.position[dim] + (camera.position[dim] - child.position[dim]) * this.speed
                ) as [number, number, number])
            );
            child.rotation.set(
                ...(dims.map(dim => 
                    child.rotation[dim] + this.rotationIncrement
                ) as [number, number, number])
            );
        });
    }
    

    Pretty sure you should be calling the .set method with the new vector values instead of reassigning the child.position or child.rotation values at the same time that you call .set.