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');