-
Notifications
You must be signed in to change notification settings - Fork 3
/
maps.go
35 lines (32 loc) · 914 Bytes
/
maps.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
package maps
import "reflect"
// Keys return map's keys as unordered slice.
func Keys(mp interface{}) interface{} {
mpValue := reflect.ValueOf(mp)
mpLen := mpValue.Len()
sliceType := reflect.SliceOf(mpValue.Type().Key())
if mpLen == 0 {
return reflect.Zero(sliceType).Interface()
}
keys := reflect.MakeSlice(sliceType, 0, mpValue.Len())
iter := mpValue.MapRange()
for iter.Next() {
keys = reflect.Append(keys, iter.Key())
}
return keys.Interface()
}
// Values return map's values as unordered slice.
func Values(mp interface{}) interface{} {
mpValue := reflect.ValueOf(mp)
mpLen := mpValue.Len()
sliceType := reflect.SliceOf(mpValue.Type().Elem())
if mpLen == 0 {
return reflect.Zero(sliceType).Interface()
}
elems := reflect.MakeSlice(sliceType, 0, mpValue.Len())
iter := mpValue.MapRange()
for iter.Next() {
elems = reflect.Append(elems, iter.Value())
}
return elems.Interface()
}