-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathflatten.go
More file actions
68 lines (58 loc) · 1.67 KB
/
flatten.go
File metadata and controls
68 lines (58 loc) · 1.67 KB
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
package weaklinq
import (
"reflect"
)
//----------------------------------------------------------------------------//
// Flatten //
//----------------------------------------------------------------------------//
////////////////////////////////////////////////////////////////////////////////
// FlattenThese returns a new Iterable where the items are flattened by the
// items returned by the selector.
func (iterable Iterable[T]) FlattenThese(selector func(T) Iterable[any]) Iterable[any] {
return Iterable[any]{
Seq: func(yield func(any) bool) {
iterable.Seq(func(item T) bool {
selector(item).Seq(func(item any) bool {
return yield(item)
})
return true
})
},
}
/*
linq.From([]T{...}).
FlattenThese(
func(item T) Iterable[any] {
return linq.From([]any{...})
},
)
*/
}
////////////////////////////////////////////////////////////////////////////////
// Flatten returns a new Iterable where the items are flattened by the
// items returned by the field name.
// If T is not a struct, or fieldName is not found, this function will panic.
func (iterable Iterable[T]) Flatten(fieldName string) Iterable[any] {
return iterable.FlattenThese(
func(item T) Iterable[any] {
result := getFieldNameFunc[T](fieldName)(item)
ref := reflect.ValueOf(result)
if ref.Kind() != reflect.Slice {
return From([]any{result})
}
return Iterable[any]{
Seq: func(yield func(any) bool) {
for i := 0; i < ref.Len(); i++ {
if !yield(ref.Index(i).Interface()) {
return
}
}
},
}
},
)
/*
linq.From([]T{...}).
Flatten("ItemField")
*/
}