Add Point Comparator Function and Tests

This commit is contained in:
Noah 2020-04-06 22:59:40 -07:00
parent 87fabf6a8d
commit bb84347294
2 changed files with 51 additions and 0 deletions

View File

@ -81,6 +81,18 @@ func (p *Point) Subtract(other Point) {
p.Y -= other.Y
}
// Compare the point to another, returning a delta coordinate.
//
// If the two points are equal the result has X=0 Y=0. Otherwise the X and Y
// return values will be positive or negative numbers of how you could modify
// the current Point to be equal to the other.
func (p *Point) Compare(other Point) Point {
return Point{
X: other.X - p.X,
Y: other.Y - p.Y,
}
}
// MarshalText to convert the point into text so that a render.Point may be used
// as a map key and serialized to JSON.
func (p *Point) MarshalText() ([]byte, error) {

View File

@ -58,3 +58,42 @@ func TestPointInside(t *testing.T) {
}
}
}
// Test the Compare function of Point.
func TestPointDelta(t *testing.T) {
var tests = []struct {
A render.Point // source
B render.Point // comparator
D render.Point // expected delta value
}{
{
A: render.NewPoint(0, 0),
B: render.NewPoint(10, 10),
D: render.NewPoint(10, 10),
},
{
A: render.NewPoint(128, 128),
B: render.NewPoint(128, 128),
D: render.NewPoint(0, 0),
},
{
A: render.NewPoint(128, 128),
B: render.NewPoint(127, 129),
D: render.NewPoint(-1, 1),
},
{
A: render.NewPoint(200, 500),
B: render.NewPoint(180, 528),
D: render.NewPoint(-20, 28),
},
}
for _, test := range tests {
actual := test.A.Compare(test.B)
if actual != test.D {
t.Errorf("Failed: (%s).Compare(%s) expected %s but got %s",
test.A, test.B, test.D, actual,
)
}
}
}