From 7c8de7ec4d30f1858c4244886bf5703d88cb523a Mon Sep 17 00:00:00 2001 From: Sikriti Dakua <38714423+devloop01@users.noreply.github.com> Date: Thu, 21 Mar 2024 23:00:15 +0530 Subject: [PATCH] feat: add `copy()` method --- .changeset/few-trees-juggle.md | 5 +++++ src/2d/vector2.ts | 14 ++++++++++++++ src/3d/vector3.ts | 15 +++++++++++++++ src/__tests__/vector2.test.ts | 9 +++++++++ 4 files changed, 43 insertions(+) create mode 100644 .changeset/few-trees-juggle.md diff --git a/.changeset/few-trees-juggle.md b/.changeset/few-trees-juggle.md new file mode 100644 index 0000000..c2dd4fe --- /dev/null +++ b/.changeset/few-trees-juggle.md @@ -0,0 +1,5 @@ +--- +'vecteur': minor +--- + +feat: add `copy()` method for `Vector2` & `Vector3` diff --git a/src/2d/vector2.ts b/src/2d/vector2.ts index 704e8c2..c4fa623 100644 --- a/src/2d/vector2.ts +++ b/src/2d/vector2.ts @@ -74,6 +74,20 @@ class Vector2 { return new Vector2(this.x, this.y) } + /** + * Copies the x and y components of another vector. + * @example + * const v1 = new Vector2(1, 2); + * const v2 = new Vector2(3, 4); + * v1.copy(v2); // v1 is now equal to v2 + * @returns this + */ + copy(v: Vector2) { + this.x = v.x + this.y = v.y + return this + } + /** * Returns an array with the x and y components of the vector. * @example diff --git a/src/3d/vector3.ts b/src/3d/vector3.ts index 8721c23..0da7495 100644 --- a/src/3d/vector3.ts +++ b/src/3d/vector3.ts @@ -90,6 +90,21 @@ class Vector3 { return new Vector3(this.x, this.y, this.z) } + /** + * Copies the x and y components of another vector. + * @example + * const v1 = new Vector2(1, 2); + * const v2 = new Vector2(3, 4); + * v1.copy(v2); // v1 is now equal to v2 + * @returns this + */ + copy(v: Vector3) { + this.x = v.x + this.y = v.y + this.z = v.z + return this + } + /** * Returns an array with the x, y and z components of the vector. * @example diff --git a/src/__tests__/vector2.test.ts b/src/__tests__/vector2.test.ts index 2ff4dbe..91e658b 100644 --- a/src/__tests__/vector2.test.ts +++ b/src/__tests__/vector2.test.ts @@ -60,6 +60,15 @@ describe('Vector2 Class', () => { }) }) + describe('copy', () => { + it('should copy the components of another vector', () => { + const vectorA = new Vector2(3, 4) + const vectorB = new Vector2().copy(vectorA) + expect(vectorB.x).toBe(vectorA.x) + expect(vectorB.y).toBe(vectorA.y) + }) + }) + describe('toArray', () => { it('should return an array with the components of the vector', () => { const vector = new Vector2(5, 6)