diff --git a/packages/geometry/README.md b/packages/geometry/README.md index f0841d82..ad11d280 100644 --- a/packages/geometry/README.md +++ b/packages/geometry/README.md @@ -3,7 +3,7 @@ [![style: very good analysis][very_good_analysis_badge]][very_good_analysis_link] [![License: MIT][license_badge]][license_link] -Helper package to calculate points of lines, arcs and curves for the pathways of the ball. +Provides a set of helpers for working with 2D geometry. [license_badge]: https://img.shields.io/badge/license-MIT-blue.svg [license_link]: https://opensource.org/licenses/MIT diff --git a/packages/geometry/lib/src/geometry.dart b/packages/geometry/lib/src/geometry.dart index 6ada92e0..8574bc73 100644 --- a/packages/geometry/lib/src/geometry.dart +++ b/packages/geometry/lib/src/geometry.dart @@ -106,3 +106,12 @@ num factorial(num n) { return n * factorial(n - 1); } } + +/// Arithmetic mean position of all the [Vector2]s in a polygon. +/// +/// For more information read: https://en.wikipedia.org/wiki/Centroid +Vector2 centroid(List vertices) { + assert(vertices.isNotEmpty, 'Vertices must not be empty'); + final sum = vertices.reduce((a, b) => a + b); + return sum / vertices.length.toDouble(); +} diff --git a/packages/geometry/pubspec.yaml b/packages/geometry/pubspec.yaml index 8fffb8b3..da305129 100644 --- a/packages/geometry/pubspec.yaml +++ b/packages/geometry/pubspec.yaml @@ -1,5 +1,5 @@ name: geometry -description: Helper package to calculate points of lines, arcs and curves for the pathways of the ball +description: Provides a set of helpers for working with 2D geometry. version: 1.0.0+1 publish_to: none diff --git a/packages/geometry/test/src/geometry_test.dart b/packages/geometry/test/src/geometry_test.dart index 2a5f9169..5c33d70f 100644 --- a/packages/geometry/test/src/geometry_test.dart +++ b/packages/geometry/test/src/geometry_test.dart @@ -166,4 +166,29 @@ void main() { }); }); }); + + group('centroid', () { + test('throws AssertionError when vertices are empty', () { + expect(() => centroid([]), throwsA(isA())); + }); + + test('is correct when one vertex is given', () { + expect(centroid([Vector2.zero()]), Vector2.zero()); + }); + + test('is correct when two vertex are given', () { + expect(centroid([Vector2.zero(), Vector2(1, 1)]), Vector2(0.5, 0.5)); + }); + + test('is correct when three vertex are given', () { + expect( + centroid([ + Vector2.zero(), + Vector2(1, 1), + Vector2(2, 2), + ]), + Vector2(1, 1), + ); + }); + }); }