From 651d529678f5aaae9a545cdb411746e2d07ae8b9 Mon Sep 17 00:00:00 2001 From: Zhang Minghan Date: Tue, 23 Jan 2024 12:04:20 +0800 Subject: [PATCH] feat: support sorted model analysis chart --- admin/analysis.go | 11 +++++++++++ admin/controller.go | 2 +- app/src/admin/colors.ts | 2 +- utils/base.go | 37 +++++++++++++++++++++++++++++++++++++ 4 files changed, 50 insertions(+), 2 deletions(-) diff --git a/admin/analysis.go b/admin/analysis.go index b2757009..31660936 100644 --- a/admin/analysis.go +++ b/admin/analysis.go @@ -59,6 +59,17 @@ func GetModelData(cache *redis.Client) ModelChartForm { } } +func GetSortedModelData(cache *redis.Client) ModelChartForm { + form := GetModelData(cache) + data := utils.Sort(form.Value, func(a ModelData, b ModelData) bool { + return utils.Sum(a.Data) > utils.Sum(b.Data) + }) + + form.Value = data + + return form +} + func GetRequestData(cache *redis.Client) RequestChartForm { dates := getDays(7) diff --git a/admin/controller.go b/admin/controller.go index 03ea9d7a..1f6bca93 100644 --- a/admin/controller.go +++ b/admin/controller.go @@ -70,7 +70,7 @@ func InfoAPI(c *gin.Context) { func ModelAnalysisAPI(c *gin.Context) { cache := utils.GetCacheFromContext(c) - c.JSON(http.StatusOK, GetModelData(cache)) + c.JSON(http.StatusOK, GetSortedModelData(cache)) } func RequestAnalysisAPI(c *gin.Context) { diff --git a/app/src/admin/colors.ts b/app/src/admin/colors.ts index 4e8c8f55..f9a2f222 100644 --- a/app/src/admin/colors.ts +++ b/app/src/admin/colors.ts @@ -77,5 +77,5 @@ export const modelColorMapper: Record = { }; export function getModelColor(model: string): string { - return modelColorMapper[model] || "#000000"; + return modelColorMapper[model] || "#111"; } diff --git a/utils/base.go b/utils/base.go index 00eb6f79..f22c99ff 100644 --- a/utils/base.go +++ b/utils/base.go @@ -175,6 +175,43 @@ func InsertChannel[T any](ch chan T, value T, index int) { } } +func Sort[T any](arr []T, compare func(a, b T) bool) []T { + if len(arr) <= 1 { + return arr + } + + var result []T + var temp []T + var hasFirst bool + var first T + + for _, item := range arr { + if !hasFirst { + first = item + hasFirst = true + continue + } + + if compare(item, first) { + temp = append(temp, item) + } else { + result = append(result, first) + result = append(result, Sort(temp, compare)...) + first = item + temp = []T{} + } + } + + if len(temp) > 0 { + result = append(result, first) + result = append(result, Sort(temp, compare)...) + } else if hasFirst { + result = append(result, first) + } + + return result +} + func Each[T any, U any](arr []T, f func(T) U) []U { var res []U for _, v := range arr {