feat(server-go): 区域发病统计(#22,rooms.region + region-stats)
This commit is contained in:
@@ -0,0 +1,44 @@
|
||||
package service
|
||||
|
||||
import "sort"
|
||||
|
||||
// RegionDiseaseEntry 区域发病条目(trace_records 联查 rooms 得到)
|
||||
type RegionDiseaseEntry struct {
|
||||
Region string
|
||||
Disease string
|
||||
}
|
||||
|
||||
// RegionStat 区域发病统计
|
||||
type RegionStat struct {
|
||||
Region string `json:"region"`
|
||||
Total int `json:"total"`
|
||||
Diseases map[string]int `json:"diseases"`
|
||||
}
|
||||
|
||||
// AggregateRegionStats 按区域分组统计发病数与病种分布(空区域剔除,按总数降序)
|
||||
func AggregateRegionStats(entries []RegionDiseaseEntry) []RegionStat {
|
||||
byRegion := make(map[string]*RegionStat)
|
||||
for _, e := range entries {
|
||||
if e.Region == "" {
|
||||
continue
|
||||
}
|
||||
s, ok := byRegion[e.Region]
|
||||
if !ok {
|
||||
s = &RegionStat{Region: e.Region, Diseases: map[string]int{}}
|
||||
byRegion[e.Region] = s
|
||||
}
|
||||
s.Total++
|
||||
s.Diseases[e.Disease]++
|
||||
}
|
||||
result := make([]RegionStat, 0, len(byRegion))
|
||||
for _, s := range byRegion {
|
||||
result = append(result, *s)
|
||||
}
|
||||
sort.Slice(result, func(i, j int) bool {
|
||||
if result[i].Total != result[j].Total {
|
||||
return result[i].Total > result[j].Total
|
||||
}
|
||||
return result[i].Region < result[j].Region
|
||||
})
|
||||
return result
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
package service
|
||||
|
||||
import "testing"
|
||||
|
||||
func TestAggregateRegionStats(t *testing.T) {
|
||||
entries := []RegionDiseaseEntry{
|
||||
{Region: "A镇", Disease: "白僵病"},
|
||||
{Region: "A镇", Disease: "白僵病"},
|
||||
{Region: "A镇", Disease: "软化病"},
|
||||
{Region: "B乡", Disease: "白僵病"},
|
||||
{Region: "", Disease: "白僵病"},
|
||||
}
|
||||
stats := AggregateRegionStats(entries)
|
||||
if len(stats) != 2 {
|
||||
t.Fatalf("统计区域数 = %d, want 2(空区域应剔除)", len(stats))
|
||||
}
|
||||
if stats[0].Region != "A镇" || stats[0].Total != 3 {
|
||||
t.Errorf("A镇应排第一且 total=3,实际 %+v", stats[0])
|
||||
}
|
||||
if stats[0].Diseases["白僵病"] != 2 || stats[0].Diseases["软化病"] != 1 {
|
||||
t.Errorf("A镇病种分布不正确: %+v", stats[0].Diseases)
|
||||
}
|
||||
if stats[1].Region != "B乡" || stats[1].Total != 1 {
|
||||
t.Errorf("B乡统计不正确: %+v", stats[1])
|
||||
}
|
||||
}
|
||||
|
||||
func TestAggregateRegionStatsEmpty(t *testing.T) {
|
||||
if len(AggregateRegionStats(nil)) != 0 {
|
||||
t.Error("空输入应返回空结果")
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user