diff --git a/point.go b/point.go index 182ecf0..e668e92 100644 --- a/point.go +++ b/point.go @@ -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) { diff --git a/point_test.go b/point_test.go index e9b9527..930030b 100644 --- a/point_test.go +++ b/point_test.go @@ -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, + ) + } + } +}