-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathmap_pipe.go
48 lines (43 loc) · 1.05 KB
/
map_pipe.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
package pipe
import (
"reflect"
)
type _MapPipe struct {
m interface{}
t reflect.Type
v reflect.Value
}
func NewMapPipe(m interface{}) *_MapPipe {
mValue := reflect.ValueOf(m)
mType := mValue.Type()
if mType.Kind() != reflect.Map {
panic("NewMapPipe only accept map param")
}
return &_MapPipe{
m: m,
v: mValue,
t: mType,
}
}
func (mp *_MapPipe) Keys() *_Pipe {
elType := mp.t.Key()
sliceType := reflect.SliceOf(elType)
keysValue := mp.v.MapKeys()
length := len(keysValue)
newSliceValue := reflect.MakeSlice(sliceType, 0, length)
for _, keyValue := range keysValue {
newSliceValue = reflect.Append(newSliceValue, keyValue)
}
return NewPipe(newSliceValue.Interface())
}
func (mp *_MapPipe) Values() *_Pipe {
elType := mp.t.Elem()
sliceType := reflect.SliceOf(elType)
keysValue := mp.v.MapKeys()
length := len(keysValue)
newSliceValue := reflect.MakeSlice(sliceType, 0, length)
for _, keyValue := range keysValue {
newSliceValue = reflect.Append(newSliceValue, mp.v.MapIndex(keyValue))
}
return NewPipe(newSliceValue.Interface())
}