Skip to content

Commit 4134e81

Browse files
feat(math): add negate operation to Vec2
1 parent 893de02 commit 4134e81

2 files changed

Lines changed: 47 additions & 3 deletions

File tree

src/core/math/Vec2.ts

Lines changed: 13 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,17 @@
11
export class Vec2 {
2-
constructor(
3-
public readonly x: number = 0,
4-
public readonly y: number = 0
2+
public constructor(
3+
public x: number = 0,
4+
public y: number = 0
55
) {
66
}
7+
8+
public negate(): void {
9+
this.x = -this.x;
10+
this.y = -this.y;
11+
}
12+
13+
public getNegated(): Vec2 {
14+
// avoid reusing negate for better performance
15+
return new Vec2(-this.x, -this.y);
16+
}
717
}

test/unit/core/math/Vec2.test.ts

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,4 +10,38 @@ describe('core/math/Vec2', () => {
1010
});
1111
})
1212
})
13+
14+
describe('.negate()', () => {
15+
it('Should negate the vector in place', () => {
16+
const vec = new Vec2(1, 2);
17+
vec.negate()
18+
expect(vec).toEqual({
19+
x: -1,
20+
y: -2
21+
});
22+
})
23+
})
24+
25+
describe('.getNegated()', () => {
26+
it('Should return a new vector with the negated values', () => {
27+
const vec = new Vec2(1, 2);
28+
const negated = vec.getNegated();
29+
30+
expect(negated).toEqual({
31+
x: -1,
32+
y: -2
33+
});
34+
})
35+
36+
it('Should not modify the original vector', () => {
37+
const vec = new Vec2(1, 2);
38+
const negated = vec.getNegated();
39+
40+
expect(negated).not.toBe(vec);
41+
expect(vec).toEqual({
42+
x: 1,
43+
y: 2
44+
});
45+
})
46+
})
1347
})

0 commit comments

Comments
 (0)