feat: included geometry method

pull/38/head
alestiago 4 years ago
parent 1ea87ca854
commit 78ce5face4

@ -105,3 +105,20 @@ num factorial(num n) {
return n * factorial(n - 1); return n * factorial(n - 1);
} }
} }
/// Arithmetic mean position of all the [Vector2]s in a figure.
///
/// For more information read: https://en.wikipedia.org/wiki/Centroid
Vector2 centroid(List<Vector2> vertices) {
assert(
vertices.isNotEmpty,
'At least one vertex needed to calculate the centroid',
);
final centroid = Vector2.zero();
for (final vertex in vertices) {
centroid.add(vertex);
}
return centroid / vertices.length.toDouble();
}

@ -156,4 +156,41 @@ void main() {
}); });
}); });
}); });
group('centroid', () {
test(
'throws AssertionError when vertices are empty',
() {
expect(() => centroid([]), throwsAssertionError);
},
);
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),
);
},
);
});
} }

Loading…
Cancel
Save