Skip to content

Commit

Permalink
test: Add tests for vector & fix: Precise loss of unit vector creation
Browse files Browse the repository at this point in the history
  • Loading branch information
NriotHrreion committed Sep 17, 2024
1 parent a3c656a commit ae7b227
Show file tree
Hide file tree
Showing 2 changed files with 74 additions and 2 deletions.
12 changes: 10 additions & 2 deletions src/simulator/vector.ts
Original file line number Diff line number Diff line change
Expand Up @@ -38,13 +38,21 @@ export class Vector implements IVector {
}

public static createUnitVector(angle: number): Vector {
return new Vector(Math.cos(angle), Math.sin(angle));
const fixedAngle = parseFloat(angle.toFixed(3));

return new Vector(Math.round(Math.cos(fixedAngle)), Math.round(Math.sin(fixedAngle)));
}
}

export class VectorCollection extends LinkedNodes<Vector> {
public constructor() {
public constructor(iterable?: Iterable<Vector>) {
super();

if(iterable) {
for(const item of iterable) {
this.push(item);
}
}
}

public getSum(): Vector {
Expand Down
64 changes: 64 additions & 0 deletions src/test/vector.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
import { Vector, VectorCollection } from "@/simulator/vector";

describe("vector-tests", () => {
it("zero-vector", () => {
const zero = Vector.Zero;

expect(zero.x).toBe(0);
expect(zero.y).toBe(0);
expect(zero.length).toBe(0);
});

it("vector-length", () => {
const vector = new Vector(3, 4);

expect(vector.length).toBe(5);
});

it("vector-addition", () => {
const vector1 = new Vector(3, 4);
const vector2 = new Vector(5, 6);

expect(Vector.add(vector1, vector2)).toEqual(new Vector(8, 10));
});

it("vector-subtraction", () => {
const vector1 = new Vector(3, 4);
const vector2 = new Vector(5, 6);

expect(Vector.sub(vector1, vector2)).toEqual(new Vector(-2, -2));
});

it("vector-multiplication", () => {
const vector1 = new Vector(3, 4);
const vector2 = new Vector(5, 6);

// 3 * 5 + 4 * 6 = 39
expect(Vector.multiply(vector1, vector2)).toBe(39);
});

it("vector-multiply-scalar", () => {
const vector = new Vector(3, 4);

expect(Vector.multiplyScalar(vector, 100)).toEqual(new Vector(300, 400));
});

it("vector-create-unit-vector", () => {
const vector = Vector.createUnitVector(Math.PI / 2);

expect(vector).toEqual(new Vector(-0, 1));
});
});

describe("vector-collection-tests", () => {
const vectors = new VectorCollection([
new Vector(3, 4),
new Vector(5, 6),
new Vector(7, 8),
new Vector(9, 10),
]);

it("sum-of-vectors", () => {
expect(vectors.getSum()).toEqual(new Vector(24, 28));
});
});

0 comments on commit ae7b227

Please sign in to comment.