-
Notifications
You must be signed in to change notification settings - Fork 12
/
xyObjectJoinX.ts
46 lines (43 loc) · 994 Bytes
/
xyObjectJoinX.ts
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
import { Point } from '../types';
export interface XYObjectJoinXOptions {
/**
* Limit to join the data.
* @default Number.EPSILON
* */
xError?: number;
}
/**
* xyObjectJoinX.
*
* @param points - Array of growing points {x,y}.
* @param options - Options.
*/
export function xyObjectJoinX(
points: Point[],
options: XYObjectJoinXOptions = {},
): Point[] {
const { xError = Number.EPSILON } = options;
// when we join we will use the center of mass
const result: Point[] = [];
let current: Point = {
x: Number.MIN_SAFE_INTEGER,
y: 0,
};
for (const point of points) {
if (point.x - current.x <= xError) {
// weighted sum
if (current.y !== 0 || point.y !== 0) {
current.x =
(point.y / (current.y + point.y)) * (point.x - current.x) + current.x;
current.y += point.y;
}
} else {
current = {
x: point.x,
y: point.y,
};
result.push(current);
}
}
return result;
}