-1

I have the following code which I wrote, but there is so much of code duplication. I would like to minimize it but I am unable to come up with the ideas. Could anyone help me out with this?

myFunc(r: Object): Object {
        if (condition) {
            return {
                x: this._width - r.w * this._cellSize - r.x * this._cellSize - CELL_PADDING * 2,
                y: this._offsetToScreen(r.y),
                w: r.w * this._cellSize - CELL_PADDING * 2,
                h: r.h * this._cellSize - CELL_PADDING * 2,
                z: r.z
            }
        } else {
            return {
                x: this._offsetToScreen(r.x),
                y: this._offsetToScreen(r.y),
                w: r.w * this._cellSize - CELL_PADDING * 2,
                h: r.h * this._cellSize - CELL_PADDING * 2,
                z: r.z
            }
        }
    }
ShellZero
  • 125

2 Answers2

1

I came up with this :)

myFunc(r: Object): Object {
        let x = this._offsetToScreen(r.x);
        if (condition) {
            x = this._width - r.w * this._cellSize - r.x * this._cellSize - CELL_PADDING * 2;
        }

        return {
            x: x,
            y: this._offsetToScreen(r.y),
            w: r.w * this._cellSize - CELL_PADDING * 2,
            h: r.h * this._cellSize - CELL_PADDING * 2,
            z: r.z
        };
    }

Thank you.

ShellZero
  • 125
0

Regardless of whether "condition" is true or false, you already know the values for everything except X. Do the computational work for y, w, h, and z before even testing "condition". Store the results in their own variables then your return statements will do the unique maths for "x" independently, but will just pass the variables computed earlier for y, w, and h. Of course "z" has no computation so you can leave it as "r.z" in both cases, no need for an intermediate variable.

myFunc(r: Object): Object {
        //the following two computations would have been executed regardless of which path the conditional path took, so just do them prior to the condition.
        width = r.w * this._cellSize - CELL_PADDING * 2;
        height = r.h * this._cellSize - CELL_PADDING * 2;
        Y = this._offsetToScreen(r.y);
        if (condition) {
            return {
                x: this._width - r.w * this._cellSize - r.x * this._cellSize - CELL_PADDING * 2,
                y: Y,
                w: width,
                h: height,
                z: r.z
            }
        } else {
            return {
                x: this._offsetToScreen(r.x),
                y: Y,
                w: width,
                h: height,
                z: r.z
            }
        }
    }
DDoomUs
  • 35