-
Notifications
You must be signed in to change notification settings - Fork 32
/
group.go
55 lines (52 loc) · 1.23 KB
/
group.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
package underscore
import (
"reflect"
)
func (m enumerable) Group(keySelector interface{}) enumerable {
return enumerable{
Enumerator: func() IEnumerator {
groupRVs := make(map[interface{}]reflect.Value)
iterator := m.GetEnumerator()
keySelectorRV := reflect.ValueOf(keySelector)
keyRVs := make([]reflect.Value, 0)
for ok := iterator.MoveNext(); ok; ok = iterator.MoveNext() {
keyRV := getReturnValue(keySelectorRV, iterator)
key := keyRV.Interface()
groupRV, ok := groupRVs[key]
if !ok {
groupRV = reflect.MakeSlice(
reflect.SliceOf(
iterator.GetValue().Type(),
),
0,
0,
)
keyRVs = append(keyRVs, keyRV)
}
groupRVs[key] = reflect.Append(
groupRV,
iterator.GetValue(),
)
}
index := 0
return &enumerator{
MoveNextFunc: func() (valueRV reflect.Value, keyRV reflect.Value, ok bool) {
if ok = index < len(keyRVs); ok {
keyRV = keyRVs[index]
valueRV = groupRVs[keyRV.Interface()]
index++
}
return
},
}
},
}
}
func (m enumerable) GroupBy(fieldName string) enumerable {
getter := FieldValue(fieldName)
return m.Group(func(value, _ interface{}) facade {
return facade{
getter(value),
}
})
}