kble/src/vec2.zig

62 lines
1.5 KiB
Zig

//! This module provides functions for creating and manipulating 2D
//! vectors with integer precision.
const expect = @import("std").testing.expect;
const Self = @This();
x: i32,
y: i32,
/// Create a vector with `x` and `y` values.
pub fn init(x: i32, y: i32) Self {
return Self {
.x = x,
.y = y,
};
}
/// Return the sum of `self` and `other`.
pub fn add(self: Self, other: Self) Self {
return Self {
.x = self.x + other.x,
.y = self.y + other.y,
};
}
/// Return the difference between `self` and `other`.
pub fn sub(self: Self, other: Self) Self {
return Self {
.x = self.x - other.x,
.y = self.y - other.y,
};
}
test "create Self w/ positive values" {
const vector = Self.init(15984, 95715);
expect(vector.x == 15984);
expect(vector.y == 95715);
}
test "create Self w/ negative values" {
const vector = Self.init(-51428, -56123);
expect(vector.x == -51428);
expect(vector.y == -56123);
}
test "add two Self using dot syntax" {
const vector_1 = Self.init(6712, 981);
const vector_2 = Self.init(-1823, 12);
const vector_sum = vector_1.add(vector_2);
expect(vector_sum.x == 4889);
expect(vector_sum.y == 993);
}
test "calculate difference between two Self using dot syntax" {
const vector_1 = Self.init(6712, 981);
const vector_2 = Self.init(-1823, 12);
const vector_diff = vector_1.sub(vector_2);
expect(vector_diff.x == 8535);
expect(vector_diff.y == 969);
}