-
Notifications
You must be signed in to change notification settings - Fork 32
/
chain.go
92 lines (83 loc) · 1.68 KB
/
chain.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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
package underscore
import (
"reflect"
)
// Chain is 创建枚举器
func Chain(src interface{}) IEnumerable {
return chainFromValue(
reflect.ValueOf(src),
)
}
func chainFromArrayOrSlice(srcValue reflect.Value, size int) IEnumerable {
return enumerable{
Enumerator: func() IEnumerator {
index := 0
return &enumerator{
MoveNextFunc: func() (valueValue reflect.Value, keyValue reflect.Value, ok bool) {
ok = index < size
if ok {
valueValue = srcValue.Index(index)
keyValue = reflect.ValueOf(index)
index++
}
return
},
}
},
}
}
func chainFromMap(srcValue reflect.Value, size int) IEnumerable {
return enumerable{
Enumerator: func() IEnumerator {
index := 0
keyValues := srcValue.MapKeys()
return &enumerator{
MoveNextFunc: func() (valueValue reflect.Value, keyValue reflect.Value, ok bool) {
ok = index < size
if ok {
valueValue = srcValue.MapIndex(keyValues[index])
keyValue = keyValues[index]
index++
}
return
},
}
},
}
}
func chainFromValue(value reflect.Value) IEnumerable {
switch value.Kind() {
case reflect.Array, reflect.Slice:
return chainFromArrayOrSlice(
value,
value.Len(),
)
case reflect.Map:
return chainFromMap(
value,
value.Len(),
)
default:
if value.IsValid() {
if iterator, ok := value.Interface().(IEnumerator); ok {
return enumerable{
Enumerator: func() IEnumerator {
return iterator
},
}
}
if value.Kind() == reflect.Ptr {
return chainFromValue(
value.Elem(),
)
}
}
return enumerable{
Enumerator: func() IEnumerator {
return nullEnumerator{
Src: value,
}
},
}
}
}