Skip to content

Commit

Permalink
Allow for polygonArea to return signed areas
Browse files Browse the repository at this point in the history
  • Loading branch information
HarryStevens committed Oct 19, 2019
1 parent ab99d27 commit 0a1d2ff
Show file tree
Hide file tree
Showing 6 changed files with 76 additions and 67 deletions.
120 changes: 60 additions & 60 deletions README.md

Large diffs are not rendered by default.

3 changes: 2 additions & 1 deletion build/geometric.js
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,7 @@

// Calculates the area of a polygon.
function polygonArea(vertices) {
var signed = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;
var a = 0;

for (var i = 0, l = vertices.length; i < l; i++) {
Expand All @@ -77,7 +78,7 @@
a -= v1[0] * v0[1];
}

return Math.abs(a / 2);
return signed ? a / 2 : Math.abs(a / 2);
}

// Calculates the bounds of a polygon.
Expand Down
1 change: 0 additions & 1 deletion build/geometric.min.js

This file was deleted.

Binary file removed build/geometric.zip
Binary file not shown.
4 changes: 2 additions & 2 deletions src/polygons/polygonArea.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
// Calculates the area of a polygon.
export function polygonArea(vertices){
export function polygonArea(vertices, signed = false){
let a = 0;

for (let i = 0, l = vertices.length; i < l; i++) {
Expand All @@ -10,5 +10,5 @@ export function polygonArea(vertices){
a -= v1[0] * v0[1];
}

return Math.abs(a / 2);
return signed ? a / 2 : Math.abs(a / 2);
}
15 changes: 12 additions & 3 deletions test/polygonArea-test.js
Original file line number Diff line number Diff line change
@@ -1,12 +1,21 @@
var tape = require("tape"),
const tape = require("tape"),
geometric = require("../");

tape("polygonArea(polygon) calculates the area of a polygon", function(test) {
tape("polygonArea(polygon) calculates the area of a polygon", test => {
test.equal(geometric.polygonArea([[0, 0], [1, 0], [1, 1], [0, 1]]), 1);
test.equal(geometric.polygonArea([[0, 0], [2, 0], [2, 2], [0, 2]]), 4);
test.equal(geometric.polygonArea([[0, 0], [3, 0], [3, 3], [0, 3]]), 9);
test.equal(geometric.polygonArea([[0, 0], [1, 0], [1, 1], [0, 1], [0, 0]]), 1);
test.equal(geometric.polygonArea([[0, 0], [2, 0], [2, 2], [0, 2], [0, 0]]), 4);
test.equal(geometric.polygonArea([[0, 0], [3, 0], [3, 3], [0, 3], [0, 0]]), 9);
test.end();
});
});

tape("If the polygon's winding order is counter-clockwise and signed is set to true, returns a negative area", test => {
const p = [[119, 87], [61, 150], [131, 197], [206, 135]];
test.equal(geometric.polygonArea(p, true), -8065);
test.equal(geometric.polygonArea(p, false), 8065);
test.equal(geometric.polygonArea(p), 8065);
test.end();
});

0 comments on commit 0a1d2ff

Please sign in to comment.