From 1712560c6e62339339e2172061561e044f9ffd34 Mon Sep 17 00:00:00 2001 From: Richard Davey Date: Tue, 3 Jan 2017 22:31:02 +0000 Subject: [PATCH] Added Point.GetCentroid. --- v3/src/geom/point/GetCentroid.js | 38 ++++++++++++++++++++++++++++++++ v3/src/geom/point/index.js | 1 + 2 files changed, 39 insertions(+) create mode 100644 v3/src/geom/point/GetCentroid.js diff --git a/v3/src/geom/point/GetCentroid.js b/v3/src/geom/point/GetCentroid.js new file mode 100644 index 000000000..5964c18c6 --- /dev/null +++ b/v3/src/geom/point/GetCentroid.js @@ -0,0 +1,38 @@ +var Point = require('./Point'); + +var GetCentroid = function (points, out) +{ + if (out === undefined) { out = new Point(); } + + if (!Array.isArray(points)) + { + throw new Error('GetCentroid points argument must be an array'); + } + + var len = points.length; + + if (len < 1) + { + throw new Error('GetCentroid points array must not be empty'); + } + else if (len === 1) + { + out.x = points[0].x; + out.y = points[0].y; + } + else + { + for (var i = 0; i < len; i++) + { + out.x += points[i].x; + out.y += points[i].y; + } + + out.x /= len; + out.y /= len; + } + + return out; +}; + +module.exports = GetCentroid; diff --git a/v3/src/geom/point/index.js b/v3/src/geom/point/index.js index a31c21b3c..c1c59199b 100644 --- a/v3/src/geom/point/index.js +++ b/v3/src/geom/point/index.js @@ -11,6 +11,7 @@ Point.Divide = require('./Divide'); Point.Dot = require('./Dot'); Point.Equals = require('./Equals'); Point.Floor = require('./Floor'); +Point.GetCentroid = require('./GetCentroid'); Point.GetMagnitude = require('./GetMagnitude'); Point.GetMagnitudeSq = require('./GetMagnitudeSq'); Point.Interpolate = require('./Interpolate');