Skip to content

Commit

Permalink
maptools/SortedKeysNoCase() (#17)
Browse files Browse the repository at this point in the history
  • Loading branch information
mmetc authored Jul 2, 2024
1 parent 499e1b6 commit 7bba11e
Show file tree
Hide file tree
Showing 2 changed files with 63 additions and 1 deletion.
24 changes: 23 additions & 1 deletion maptools/sort.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
package maptools

import "sort"
import (
"sort"
"strings"
)

func SortedKeys[V any](m map[string]V) []string {
keys := make([]string, 0, len(m))
Expand All @@ -12,3 +15,22 @@ func SortedKeys[V any](m map[string]V) []string {

return keys
}

func SortedKeysNoCase[V any](m map[string]V) []string {
keys := make([]string, 0, len(m))
for k := range m {
keys = append(keys, k)
}

sort.Slice(keys, func(i, j int) bool {
li, lj := strings.ToLower(keys[i]), strings.ToLower(keys[j])
if li == lj {
// differ only by case, sort by original key
// will have uppercase first
return keys[i] < keys[j]
}
return li < lj
})

return keys
}
40 changes: 40 additions & 0 deletions maptools/sort_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -40,3 +40,43 @@ func TestSortedKeys(t *testing.T) {
})
}
}

func TestSortedKeysNoCase(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 with different cases",
m: map[string]int{"b": 2, "A": 1, "C": 3},
want: []string{"A", "b", "C"},
},
{
name: "elements with same values and different cases",
m: map[string]int{"b": 2, "A": 2, "c": 2},
want: []string{"A", "b", "c"},
},
{
name: "mixed case elements",
m: map[string]int{"Banana": 1, "apple": 2, "Cherry": 3, "banana": 4, "Apple": 5, "cherry": 6},
want: []string{"Apple", "apple", "Banana", "banana", "Cherry", "cherry"},
},
}

for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
assert.Equal(t, tt.want, SortedKeysNoCase(tt.m))
})
}
}

0 comments on commit 7bba11e

Please sign in to comment.