github.com/coreos/mantle@v0.13.0/lang/maps/sorted.go (about) 1 // Copyright 2016 CoreOS, Inc. 2 // 3 // Licensed under the Apache License, Version 2.0 (the "License"); 4 // you may not use this file except in compliance with the License. 5 // You may obtain a copy of the License at 6 // 7 // http://www.apache.org/licenses/LICENSE-2.0 8 // 9 // Unless required by applicable law or agreed to in writing, software 10 // distributed under the License is distributed on an "AS IS" BASIS, 11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 // See the License for the specific language governing permissions and 13 // limitations under the License. 14 15 package maps 16 17 import ( 18 "reflect" 19 "sort" 20 21 "github.com/coreos/mantle/lang/natsort" 22 ) 23 24 // Keys returns a map's keys as an unordered slice of strings. 25 func Keys(m interface{}) []string { 26 mapValue := reflect.ValueOf(m) 27 28 // Value.String() isn't sufficient to assert the keys are strings. 29 if mapValue.Type().Key().Kind() != reflect.String { 30 panic("maps: keys must be strings") 31 } 32 33 keyValues := mapValue.MapKeys() 34 keys := make([]string, len(keyValues)) 35 for i, k := range keyValues { 36 keys[i] = k.String() 37 } 38 39 return keys 40 } 41 42 // SortedKeys returns a map's keys as a sorted slice of strings. 43 func SortedKeys(m interface{}) []string { 44 keys := Keys(m) 45 sort.Strings(keys) 46 return keys 47 } 48 49 // NaturalKeys returns a map's keys as a natural sorted slice of strings. 50 // See github.com/coreos/mantle/lang/natsort 51 func NaturalKeys(m interface{}) []string { 52 keys := Keys(m) 53 natsort.Strings(keys) 54 return keys 55 }