From e11df2ef5d161278928f78d53bd14a26430ca6f9 Mon Sep 17 00:00:00 2001 From: John Wang Date: Mon, 27 Nov 2023 01:33:02 -0800 Subject: [PATCH] feat: `type/slicesutil`: add `LengthCounts()`, `Sort()` --- type/slicesutil/slice.go | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) diff --git a/type/slicesutil/slice.go b/type/slicesutil/slice.go index b227224..9b3ebf9 100644 --- a/type/slicesutil/slice.go +++ b/type/slicesutil/slice.go @@ -22,6 +22,16 @@ func Dedupe[S ~[]E, E comparable](s S) S { return deduped } +// LengthCounts returns a `map[uint]uint` where the keys are element lengths and the values +// are counts of slices with those lenghts. +func LengthCounts[E any](s [][]E) map[uint]uint { + stats := map[uint]uint{} + for _, si := range s { + stats[uint(len(si))]++ + } + return stats +} + func ElementCounts[E comparable](s []E) map[E]int { m := map[E]int{} for _, si := range s { @@ -78,6 +88,12 @@ func Shift[S ~[]E, E any](s S) (E, S) { return s[0], s[1:] } +func Sort[E constraints.Ordered](s []E) { + sort.Slice(s, func(i, j int) bool { + return s[i] < s[j] + }) +} + func SortSliceOfSlice[S ~[][]E, E constraints.Ordered | string](s S, indexes ...uint) { for _, idx := range indexes { sort.Slice(s, func(i, j int) bool {