forked from thoas/go-funk
-
Notifications
You must be signed in to change notification settings - Fork 0
/
map.go
74 lines (51 loc) · 1.56 KB
/
map.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
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
package funk
import (
"fmt"
"reflect"
)
// Keys creates an array of the own enumerable map keys or struct field names.
func Keys(out interface{}) interface{} {
value := redirectValue(reflect.ValueOf(out))
valueType := value.Type()
if value.Kind() == reflect.Map {
keys := value.MapKeys()
length := len(keys)
resultSlice := reflect.MakeSlice(reflect.SliceOf(valueType.Key()), length, length)
for i, key := range keys {
resultSlice.Index(i).Set(key)
}
return resultSlice.Interface()
}
if value.Kind() == reflect.Struct {
length := value.NumField()
resultSlice := make([]string, length)
for i := 0; i < length; i++ {
resultSlice[i] = valueType.Field(i).Name
}
return resultSlice
}
panic(fmt.Sprintf("Type %s is not supported by Keys", valueType.String()))
}
// Values creates an array of the own enumerable map values or struct field values.
func Values(out interface{}) interface{} {
value := redirectValue(reflect.ValueOf(out))
valueType := value.Type()
if value.Kind() == reflect.Map {
keys := value.MapKeys()
length := len(keys)
resultSlice := reflect.MakeSlice(reflect.SliceOf(valueType.Elem()), length, length)
for i, key := range keys {
resultSlice.Index(i).Set(value.MapIndex(key))
}
return resultSlice.Interface()
}
if value.Kind() == reflect.Struct {
length := value.NumField()
resultSlice := make([]interface{}, length)
for i := 0; i < length; i++ {
resultSlice[i] = value.Field(i).Interface()
}
return resultSlice
}
panic(fmt.Sprintf("Type %s is not supported by Keys", valueType.String()))
}