-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathweakLinq.go
More file actions
80 lines (60 loc) · 2.24 KB
/
weakLinq.go
File metadata and controls
80 lines (60 loc) · 2.24 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
69
70
71
72
73
74
75
76
77
78
79
80
package weaklinq
import (
"fmt"
"iter"
"reflect"
"slices"
)
//----------------------------------------------------------------------------//
// Common //
//----------------------------------------------------------------------------//
////////////////////////////////////////////////////////////////////////////////
// Iterable is the base structure for an iterable. It allows for the lazy
// iteration of a collection of items and exists to allow functions to be
// called on the collection.
type Iterable[T any] struct {
iter.Seq[T]
}
////////////////////////////////////////////////////////////////////////////////
// identitySelector is a function that returns the item passed to it. Used as
// the default selector for many functions.
func identitySelector[T any](item T) any {
return item
}
////////////////////////////////////////////////////////////////////////////////
// getFieldNameFunc returns a function that returns the value of the given
// field name. If T is not a struct or pointer to struct, or fieldName is
// not found, this function will panic.
func getFieldNameFunc[T any](fieldName string) func(T) any {
return func(item T) any {
res := reflect.ValueOf(item)
if res.Kind() != reflect.Struct {
if res.Kind() == reflect.Pointer {
if reflect.Indirect(res).Kind() != reflect.Struct {
panic(fmt.Sprintf("item is a pointer, but not to a struct: %T", item))
}
res = res.Elem()
} else {
panic(fmt.Sprintf("item is not a struct or pointer to struct: %T", item))
}
}
field := res.FieldByName(fieldName)
if !field.IsValid() {
panic(fmt.Sprintf("field name '%s' not found in struct %T", fieldName, item))
}
return field.Interface()
}
}
//----------------------------------------------------------------------------//
// Constructors //
//----------------------------------------------------------------------------//
////////////////////////////////////////////////////////////////////////////////
// From creates a new Iterable from a slice of items.
func From[T any](items []T) Iterable[T] {
return Iterable[T]{
Seq: slices.Values(items),
}
/*
linq.From([]T{...})
*/
}