-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcluster.js
58 lines (44 loc) · 1.35 KB
/
cluster.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
function Cluster(points) {
var self = this;
this.points = points || [];
this.add = function (obj) {
var arr = obj;
if (obj instanceof Point)
arr = [obj];
for (var i = 0; i < arr.length; i++)
this.points.push(arr[i]);
updateCentroid();
}
this.remove = function (point) {
this.points.remove(point);
updateCentroid();
}
this.getPointNearestToCentroid = function () {
if (!this.points.length)
return null;
var minimumDistance = Number.MAX_VALUE;
var nearestPoint = null;
for (var i = 0; i < this.points.length; i++) {
var p = this.points[i];
var distance = p.getDistance(this.centroid);
if (distance < minimumDistance) {
minimumDistance = distance;
nearestPoint = p;
}
}
return nearestPoint;
}
function updateCentroid() {
if (!self.points.length) {
self.centroid = new Point(0, 0);
return;
}
var xSum = 0, ySum = 0;
for (var i = 0; i < self.points.length; i++) {
xSum += self.points[i].x;
ySum += self.points[i].y;
}
self.centroid = new Point(xSum / self.points.length, ySum / self.points.length);
}
updateCentroid();
}