mirror of
				https://github.com/Unleash/unleash.git
				synced 2025-10-27 11:02:16 +01:00 
			
		
		
		
	refactor: improve performance of collapseHourlyMetrics (#1945)
This commit is contained in:
		
							parent
							
								
									b5fead41f6
								
							
						
					
					
						commit
						b8b802c8ed
					
				| @ -1,17 +1,6 @@ | ||||
| import { IClientMetricsEnv } from '../types/stores/client-metrics-store-v2'; | ||||
| import { startOfHour } from 'date-fns'; | ||||
| 
 | ||||
| const groupBy = <T>(list: T[], createKey: (item: T) => string): T[][] => { | ||||
|     const groups = list.reduce((acc, item) => { | ||||
|         const key = createKey(item); | ||||
|         acc[key] = acc[key] ?? []; | ||||
|         acc[key].push(item); | ||||
|         return acc; | ||||
|     }, {} as Record<string, T[]>); | ||||
| 
 | ||||
|     return Object.values(groups); | ||||
| }; | ||||
| 
 | ||||
| const createMetricKey = (metric: IClientMetricsEnv): string => { | ||||
|     return [ | ||||
|         metric.featureName, | ||||
| @ -21,31 +10,22 @@ const createMetricKey = (metric: IClientMetricsEnv): string => { | ||||
|     ].join(); | ||||
| }; | ||||
| 
 | ||||
| const sumYesNo = ( | ||||
|     metrics: IClientMetricsEnv[], | ||||
| ): Pick<IClientMetricsEnv, 'yes' | 'no'> => { | ||||
|     return metrics.reduce( | ||||
|         (acc, metric) => ({ | ||||
|             yes: acc.yes + metric.yes, | ||||
|             no: acc.no + metric.no, | ||||
|         }), | ||||
|         { | ||||
|             yes: 0, | ||||
|             no: 0, | ||||
|         }, | ||||
|     ); | ||||
| }; | ||||
| 
 | ||||
| export const collapseHourlyMetrics = ( | ||||
|     metrics: IClientMetricsEnv[], | ||||
| ): IClientMetricsEnv[] => { | ||||
|     const hourlyMetrics = metrics.map((metric) => ({ | ||||
|         ...metric, | ||||
|         timestamp: startOfHour(metric.timestamp), | ||||
|     })); | ||||
| 
 | ||||
|     return groupBy(hourlyMetrics, createMetricKey).flatMap((group) => ({ | ||||
|         ...group[0], | ||||
|         ...sumYesNo(group), | ||||
|     })); | ||||
|     const grouped = new Map<string, IClientMetricsEnv>(); | ||||
|     metrics.forEach((metric) => { | ||||
|         const hourlyMetric = { | ||||
|             ...metric, | ||||
|             timestamp: startOfHour(metric.timestamp), | ||||
|         }; | ||||
|         const key = createMetricKey(hourlyMetric); | ||||
|         if (!grouped[key]) { | ||||
|             grouped[key] = hourlyMetric; | ||||
|         } else { | ||||
|             grouped[key].yes = metric.yes + (grouped[key].yes || 0); | ||||
|             grouped[key].no = metric.no + (grouped[key].no || 0); | ||||
|         } | ||||
|     }); | ||||
|     return Object.values(grouped); | ||||
| }; | ||||
|  | ||||
		Loading…
	
		Reference in New Issue
	
	Block a user