diff --git a/sort/sort.go b/sort/sort.go new file mode 100644 index 0000000..a8b0b04 --- /dev/null +++ b/sort/sort.go @@ -0,0 +1,69 @@ +package sort + +import ( + "sort" + "strings" +) + +type mapSorter[T any] struct { + keys []string + m map[string]T +} + +func SortByKey[T any](m map[string]T) *mapSorter[T] { + return &mapSorter[T]{ + m: m, + keys: keys(m), + } +} + +func (s *mapSorter[T]) Asc() *mapSorter[T] { + keys := s.keys + sort.Strings(keys) + + return &mapSorter[T]{ + m: s.m, + keys: keys, + } +} + +func (s *mapSorter[T]) Desc() *mapSorter[T] { + keys := s.keys + sort.Sort(sort.Reverse(sort.StringSlice(keys))) + + return &mapSorter[T]{ + m: s.m, + keys: keys, + } +} + +func (s *mapSorter[T]) Join(sep string, f func(k string, v T) string) string { + slice := make([]string, 0, len(s.m)) + for _, k := range s.keys { + slice = append(slice, f(k, s.m[k])) + } + + return strings.Join(slice, sep) +} + +func (s *mapSorter[T]) Keys() []string { + return s.keys +} + +func (s *mapSorter[T]) Values() []T { + ret := make([]T, 0, len(s.m)) + for _, k := range s.keys { + ret = append(ret, s.m[k]) + } + + return ret +} + +func keys[T any](m map[string]T) []string { + keys := make([]string, 0, len(m)) + for k := range m { + keys = append(keys, k) + } + + return keys +} diff --git a/sort/sort_test.go b/sort/sort_test.go new file mode 100644 index 0000000..133f316 --- /dev/null +++ b/sort/sort_test.go @@ -0,0 +1,42 @@ +package sort + +import ( + "fmt" + "testing" +) + +func TestSort(t *testing.T) { + m := map[string]any{ + "Bcd": "bcd", + "Abc": "abc", + } + + t.Log(SortByKey(m).Values()) + t.Log(SortByKey(m).Desc().Values()) + t.Log(SortByKey(m).Asc().Values()) +} + +func TestMapSortInt(t *testing.T) { + m := map[string]int{ + "Bcd": 8, + "Abc": 4, + } + + ret := SortByKey(m).Desc().Values() + + t.Log(ret) +} + +func TestJoin(t *testing.T) { + m := map[string]any{ + "Bcd": "bcd", + "Abc": "abc", + "Efg": "efg", + } + + j := SortByKey(m).Asc().Join("&", func(k string, v any) string { + return fmt.Sprintf("%s=%v", k, v) + }) + + t.Log(j) +}