From 7cbd3d117a3c8075027cffaad2cab38b21cc9de6 Mon Sep 17 00:00:00 2001 From: Oleksandr Redko Date: Fri, 13 Dec 2024 19:57:34 +0200 Subject: [PATCH] refactor: use slices.SortFunc instead of sort.Slice (#1191) --- formatter/friendly.go | 9 ++++---- formatter/friendly_test.go | 46 ++++++++++++++++++++++++++++++++++++++ 2 files changed, 51 insertions(+), 4 deletions(-) create mode 100644 formatter/friendly_test.go diff --git a/formatter/friendly.go b/formatter/friendly.go index 342ce35a6..9c1a0f617 100644 --- a/formatter/friendly.go +++ b/formatter/friendly.go @@ -2,9 +2,10 @@ package formatter import ( "bytes" + "cmp" "fmt" "io" - "sort" + "slices" "strings" "github.com/fatih/color" @@ -112,12 +113,12 @@ func (f *Friendly) printStatistics(w io.Writer, header string, stats map[string] if len(stats) == 0 { return } - var data []statEntry + data := make([]statEntry, 0, len(stats)) for name, total := range stats { data = append(data, statEntry{name, total}) } - sort.Slice(data, func(i, j int) bool { - return data[i].failures > data[j].failures + slices.SortFunc(data, func(a, b statEntry) int { + return -cmp.Compare(a.failures, b.failures) }) formatted := [][]string{} for _, entry := range data { diff --git a/formatter/friendly_test.go b/formatter/friendly_test.go new file mode 100644 index 000000000..e0deb900f --- /dev/null +++ b/formatter/friendly_test.go @@ -0,0 +1,46 @@ +package formatter + +import ( + "bytes" + "testing" +) + +func TestFriendly_printStatistics(t *testing.T) { + tests := []struct { + name string + stats map[string]int + expected string + }{ + { + name: "no stats", + stats: map[string]int{}, + expected: "", + }, + { + name: "nil stats", + stats: nil, + expected: "", + }, + { + name: "single stat", + stats: map[string]int{"rule1": 1}, + expected: "Warnings:\n 1 rule1 \n\n", + }, + { + name: "multiple stats sorted by failures desc", + stats: map[string]int{"rule2": 2, "rule1": 1, "rule3": 3}, + expected: "Warnings:\n 3 rule3 \n 2 rule2 \n 1 rule1 \n\n", + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + f := &Friendly{} + var buf bytes.Buffer + f.printStatistics(&buf, "Warnings:", tt.stats) + if got := buf.String(); got != tt.expected { + t.Errorf("got %q, want %q", got, tt.expected) + } + }) + } +}