Add SortedStringValues and SortedUniqueStringValues
Add SortedStringValues and SortedUniqueStringValues that return the values of a string-valued map. Also make the SortedStringKeys function use a similar implementation with MapRange, which avoids iterating over the keys twice, once in MapKeys to build the list of key reflect.Values and once over the reflect.Values to convert them to strings. Test: util_test.go Change-Id: I4fc990a5036421e8926094ee158fafe606d0f10b
This commit is contained in:
@@ -65,21 +65,55 @@ func JoinWithSuffix(strs []string, suffix string, separator string) string {
|
||||
return buf.String()
|
||||
}
|
||||
|
||||
// SorterStringKeys returns the keys of the given string-keyed map in the ascending order
|
||||
// SorterStringKeys returns the keys of the given string-keyed map in the ascending order.
|
||||
func SortedStringKeys(m interface{}) []string {
|
||||
v := reflect.ValueOf(m)
|
||||
if v.Kind() != reflect.Map {
|
||||
panic(fmt.Sprintf("%#v is not a map", m))
|
||||
}
|
||||
keys := v.MapKeys()
|
||||
s := make([]string, 0, len(keys))
|
||||
for _, key := range keys {
|
||||
s = append(s, key.String())
|
||||
if v.Len() == 0 {
|
||||
return nil
|
||||
}
|
||||
iter := v.MapRange()
|
||||
s := make([]string, 0, v.Len())
|
||||
for iter.Next() {
|
||||
s = append(s, iter.Key().String())
|
||||
}
|
||||
sort.Strings(s)
|
||||
return s
|
||||
}
|
||||
|
||||
// stringValues returns the values of the given string-valued map in randomized map order.
|
||||
func stringValues(m interface{}) []string {
|
||||
v := reflect.ValueOf(m)
|
||||
if v.Kind() != reflect.Map {
|
||||
panic(fmt.Sprintf("%#v is not a map", m))
|
||||
}
|
||||
if v.Len() == 0 {
|
||||
return nil
|
||||
}
|
||||
iter := v.MapRange()
|
||||
s := make([]string, 0, v.Len())
|
||||
for iter.Next() {
|
||||
s = append(s, iter.Value().String())
|
||||
}
|
||||
return s
|
||||
}
|
||||
|
||||
// SortedStringValues returns the values of the given string-valued map in the ascending order.
|
||||
func SortedStringValues(m interface{}) []string {
|
||||
s := stringValues(m)
|
||||
sort.Strings(s)
|
||||
return s
|
||||
}
|
||||
|
||||
// SortedUniqueStringValues returns the values of the given string-valued map in the ascending order
|
||||
// with duplicates removed.
|
||||
func SortedUniqueStringValues(m interface{}) []string {
|
||||
s := stringValues(m)
|
||||
return SortedUniqueStrings(s)
|
||||
}
|
||||
|
||||
// IndexList returns the index of the first occurrence of the given string in the list or -1
|
||||
func IndexList(s string, list []string) int {
|
||||
for i, l := range list {
|
||||
|
Reference in New Issue
Block a user