-
-
Notifications
You must be signed in to change notification settings - Fork 658
/
useFilteredFlagsSummary.ts
77 lines (68 loc) · 2.67 KB
/
useFilteredFlagsSummary.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
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
import { useMemo } from 'react';
import type {
InstanceInsightsSchemaProjectFlagTrendsItem,
InstanceInsightsSchemaUsers,
} from 'openapi';
const validTimeToProduction = (
item: InstanceInsightsSchemaProjectFlagTrendsItem,
) => Boolean(item) && typeof item.timeToProduction === 'number';
// NOTE: should we move project filtering to the backend?
export const useFilteredFlagsSummary = (
filteredProjectFlagTrends: InstanceInsightsSchemaProjectFlagTrendsItem[],
users: InstanceInsightsSchemaUsers,
) =>
useMemo(() => {
const lastWeekId = filteredProjectFlagTrends.reduce((prev, current) => {
if (current.week > prev) return current.week;
return prev;
}, '');
const lastWeekSummary = filteredProjectFlagTrends.filter(
(summary) => summary.week === lastWeekId,
);
const averageUsers =
lastWeekSummary.reduce(
(acc, current) => acc + (current.users || 0),
0,
) / lastWeekSummary.length || 0;
const sum = lastWeekSummary.reduce(
(acc, current) => ({
total: acc.total + current.total,
active: acc.active + current.active,
stale: acc.stale + current.stale,
potentiallyStale:
acc.potentiallyStale + current.potentiallyStale,
averageUsers,
}),
{
total: 0,
active: 0,
stale: 0,
potentiallyStale: 0,
},
);
const timesToProduction: number[] = lastWeekSummary
.filter(validTimeToProduction)
.map((item) => item.timeToProduction!); // Non-null assertion is safe due to filter
// Calculate median timeToProduction for lastWeekSummary
timesToProduction.sort((a, b) => a - b);
const midIndex = Math.floor(timesToProduction.length / 2);
const medianTimeToProduction =
timesToProduction.length % 2 === 0
? (timesToProduction[midIndex - 1] +
timesToProduction[midIndex]) /
2
: timesToProduction[midIndex];
const flagsPerUserCalculation = sum.total / users.total;
const flagsPerUser = Number.isNaN(flagsPerUserCalculation)
? 'N/A'
: flagsPerUserCalculation.toFixed(2);
return {
...sum,
flagsPerUser,
averageUsers,
averageHealth: sum.total
? ((sum.active / (sum.total || 1)) * 100).toFixed(0)
: undefined,
medianTimeToProduction,
};
}, [filteredProjectFlagTrends]);