diff --git a/maptools/sort.go b/maptools/sort.go new file mode 100644 index 0000000..7088adc --- /dev/null +++ b/maptools/sort.go @@ -0,0 +1,14 @@ +package maptools + +import "sort" + +func SortedKeys[V any](m map[string]V) []string { + keys := make([]string, 0, len(m)) + for k := range m { + keys = append(keys, k) + } + + sort.Strings(keys) + + return keys +} diff --git a/maptools/sort_test.go b/maptools/sort_test.go new file mode 100644 index 0000000..0043ec6 --- /dev/null +++ b/maptools/sort_test.go @@ -0,0 +1,42 @@ +package maptools + +import ( + "testing" + + "github.com/stretchr/testify/assert" +) + +func TestSortedKeys(t *testing.T) { + tests := []struct { + name string + m map[string]int + want []string + }{ + { + name: "empty map", + m: map[string]int{}, + want: []string{}, + }, + { + name: "single element", + m: map[string]int{"a": 1}, + want: []string{"a"}, + }, + { + name: "multiple elements", + m: map[string]int{"b": 2, "a": 1, "c": 3}, + want: []string{"a", "b", "c"}, + }, + { + name: "elements with same values", + m: map[string]int{"b": 2, "a": 2, "c": 2}, + want: []string{"a", "b", "c"}, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + assert.Equal(t, tt.want, SortedKeys(tt.m)) + }) + } +}