diff --git a/packages/mads-vec2/src/index.ts b/packages/mads-vec2/src/index.ts index d42b651d..5ee22cba 100644 --- a/packages/mads-vec2/src/index.ts +++ b/packages/mads-vec2/src/index.ts @@ -2,10 +2,7 @@ export class Vector2 { constructor(public x = 0, public y = 0) {} public get length() { - const x = this.x; - const y = this.y; - - return Math.sqrt(x * x + y * y); + return Math.sqrt(this.x * this.x + this.y * this.y); } public add(vector: Vector2) { @@ -34,8 +31,10 @@ export class Vector2 { } public normalize() { - this.x /= this.length; - this.y /= this.length; + const length = this.length; + + this.x /= length; + this.y /= length; } // Angle in rad. diff --git a/packages/mads-vec2/tests/index.spec.ts b/packages/mads-vec2/tests/index.spec.ts index 70c97a19..33d7ca8f 100644 --- a/packages/mads-vec2/tests/index.spec.ts +++ b/packages/mads-vec2/tests/index.spec.ts @@ -71,6 +71,7 @@ describe("mads-vec2", () => { it("Vector2.normalize", () => { const a = new Vector2(5, 0); const b = new Vector2(0, -5); + const c = new Vector2(2, 5); a.normalize(); expect(a.length).toBe(1); @@ -79,6 +80,11 @@ describe("mads-vec2", () => { b.normalize(); expect(b.length).toBe(1); expect(b.y).toBe(-1); + + c.normalize(); + expect(c.length).toBeCloseTo(1); + expect(c.x).toBeCloseTo(0.37139068, 7); + expect(c.y).toBeCloseTo(0.92847669, 7); }); it("Vector2.rotate", () => { diff --git a/packages/mads-vec3/src/index.ts b/packages/mads-vec3/src/index.ts index 59cad383..2585d874 100644 --- a/packages/mads-vec3/src/index.ts +++ b/packages/mads-vec3/src/index.ts @@ -2,11 +2,7 @@ export class Vector3 { constructor(public x = 0, public y = 0, public z = 0) {} public get length() { - const x = this.x; - const y = this.y; - const z = this.z; - - return Math.sqrt(x * x + y * y + z * z); + return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z); } public add(vector: Vector3) { @@ -40,9 +36,11 @@ export class Vector3 { } public normalize() { - this.x /= this.length; - this.y /= this.length; - this.z /= this.length; + const length = this.length; + + this.x /= length; + this.y /= length; + this.z /= length; } public equals(vector: Vector3) { diff --git a/packages/mads-vec3/tests/index.spec.ts b/packages/mads-vec3/tests/index.spec.ts index 6a96ef1f..76cb1035 100644 --- a/packages/mads-vec3/tests/index.spec.ts +++ b/packages/mads-vec3/tests/index.spec.ts @@ -81,6 +81,7 @@ describe("mads-vec3", () => { const a = new Vector3(5, 0, 0); const b = new Vector3(0, -5, 0); const c = new Vector3(0, 0, -5); + const d = new Vector3(2, 3, 4); a.normalize(); expect(a.length).toBe(1); @@ -93,6 +94,12 @@ describe("mads-vec3", () => { c.normalize(); expect(c.length).toBe(1); expect(c.z).toBe(-1); + + d.normalize(); + expect(d.length).toBeCloseTo(1); + expect(d.x).toBeCloseTo(0.371391, 5); + expect(d.y).toBeCloseTo(0.557086, 5); + expect(d.z).toBeCloseTo(0.742781, 5); }); it("Vector3.equals", () => {