diff --git a/src/hull.js b/src/hull.js index daaf9a5..2314105 100644 --- a/src/hull.js +++ b/src/hull.js @@ -4,16 +4,16 @@ function lexicographicOrder(a, b) { return a[0] - b[0] || a[1] - b[1]; } -// Computes the upper convex hull per the monotone chain algorithm. +// Computes the upper (sign = 1) or lower (sign = -1) convex hull per the monotone chain algorithm. // Assumes points.length >= 3, is sorted by x, unique in y. // Returns an array of indices into points in left-to-right order. -function computeUpperHullIndexes(points) { +function computeHullIndexes(points, sign) { const n = points.length, indexes = [0, 1]; let size = 2, i; for (i = 2; i < n; ++i) { - while (size > 1 && cross(points[indexes[size - 2]], points[indexes[size - 1]], points[i]) <= 0) --size; + while (size > 1 && sign * cross(points[indexes[size - 2]], points[indexes[size - 1]], points[i]) <= 0) --size; indexes[size++] = i; } @@ -25,15 +25,13 @@ export default function(points) { var i, n, - sortedPoints = new Array(n), - flippedPoints = new Array(n); + sortedPoints = new Array(n); for (i = 0; i < n; ++i) sortedPoints[i] = [+points[i][0], +points[i][1], i]; sortedPoints.sort(lexicographicOrder); - for (i = 0; i < n; ++i) flippedPoints[i] = [sortedPoints[i][0], -sortedPoints[i][1]]; - var upperIndexes = computeUpperHullIndexes(sortedPoints), - lowerIndexes = computeUpperHullIndexes(flippedPoints); + var upperIndexes = computeHullIndexes(sortedPoints, 1), + lowerIndexes = computeHullIndexes(sortedPoints, -1); // Construct the hull polygon, removing possible duplicate endpoints. var skipLeft = lowerIndexes[0] === upperIndexes[0], diff --git a/src/length.js b/src/length.js index 8e4da5e..79a90b8 100644 --- a/src/length.js +++ b/src/length.js @@ -16,7 +16,7 @@ export default function(polygon) { yb = b[1]; xa -= xb; ya -= yb; - perimeter += Math.hypot(xa, ya); + perimeter += Math.sqrt(xa * xa + ya * ya); } return perimeter;