Skip to content

Commit

Permalink
feat(math): add negate operation to Vec2
Browse files Browse the repository at this point in the history
  • Loading branch information
RuggeroVisintin committed Dec 12, 2023
1 parent 893de02 commit 4134e81
Show file tree
Hide file tree
Showing 2 changed files with 47 additions and 3 deletions.
16 changes: 13 additions & 3 deletions src/core/math/Vec2.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,17 @@
export class Vec2 {
constructor(
public readonly x: number = 0,
public readonly y: number = 0
public constructor(
public x: number = 0,
public y: number = 0
) {
}

public negate(): void {
this.x = -this.x;
this.y = -this.y;
}

public getNegated(): Vec2 {
// avoid reusing negate for better performance
return new Vec2(-this.x, -this.y);
}
}
34 changes: 34 additions & 0 deletions test/unit/core/math/Vec2.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,4 +10,38 @@ describe('core/math/Vec2', () => {
});
})
})

describe('.negate()', () => {
it('Should negate the vector in place', () => {
const vec = new Vec2(1, 2);
vec.negate()
expect(vec).toEqual({
x: -1,
y: -2
});
})
})

describe('.getNegated()', () => {
it('Should return a new vector with the negated values', () => {
const vec = new Vec2(1, 2);
const negated = vec.getNegated();

expect(negated).toEqual({
x: -1,
y: -2
});
})

it('Should not modify the original vector', () => {
const vec = new Vec2(1, 2);
const negated = vec.getNegated();

expect(negated).not.toBe(vec);
expect(vec).toEqual({
x: 1,
y: 2
});
})
})
})

0 comments on commit 4134e81

Please sign in to comment.