forked from BasedHardware/omi
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathperiod-change.ts
More file actions
53 lines (47 loc) · 1.21 KB
/
Copy pathperiod-change.ts
File metadata and controls
53 lines (47 loc) · 1.21 KB
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
export interface PeriodChange {
percentage: number;
label: string;
}
type MetricValue = number | null | undefined;
export function calculatePeriodChange(
current: MetricValue,
previous: MetricValue,
label = "vs previous period",
): PeriodChange | null {
if (
current == null ||
previous == null ||
!Number.isFinite(current) ||
!Number.isFinite(previous)
) {
return null;
}
if (previous === 0) {
return current === 0 ? { percentage: 0, label } : null;
}
return {
percentage: ((current - previous) / Math.abs(previous)) * 100,
label,
};
}
export function latestPeriodChange<T>(
points: readonly T[],
value: (point: T) => MetricValue,
label = "vs previous period",
): PeriodChange | null {
if (points.length < 2) return null;
return calculatePeriodChange(
value(points[points.length - 1]),
value(points[points.length - 2]),
label,
);
}
export function formatPeriodChange(percentage: number): string {
const normalized = Math.abs(percentage) < 0.05 ? 0 : percentage;
return (
new Intl.NumberFormat("en-US", {
signDisplay: "exceptZero",
maximumFractionDigits: Math.abs(normalized) >= 10 ? 0 : 1,
}).format(normalized) + "%"
);
}