-
Notifications
You must be signed in to change notification settings - Fork 1
/
helpers.go
115 lines (100 loc) · 2.38 KB
/
helpers.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
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
package collect
import (
"errors"
"fmt"
"reflect"
"strconv"
)
func AnyGet[V, K any](item any, key K) (zero V, _ error) {
var result any
ref := reflect.ValueOf(item)
switch ref.Kind() {
case reflect.Map:
if r := ref.MapIndex(reflect.ValueOf(key)); r.IsValid() {
result = r.Interface()
} else {
return zero, errors.New("invalid map index")
}
case reflect.Array, reflect.Slice:
if index, err := strconv.Atoi(fmt.Sprintf("%v", key)); err != nil {
return zero, err
} else {
if index < 0 || index >= ref.Len() {
return zero, errors.New("index overflow")
}
result = ref.Index(index).Interface()
}
case reflect.Struct:
if r := ref.FieldByName(fmt.Sprintf("%v", key)); r.IsValid() {
result = r.Interface()
} else {
return zero, errors.New("invalid struct field")
}
case reflect.Pointer:
return AnyGet[V, K](ref.Elem().Interface(), key)
default:
return zero, errors.New("failed to get")
}
switch result.(type) {
case V:
return result.(V), nil
default:
return zero, errors.New("type mismatch")
}
}
func Pluck[V, K, I any](items []I, key K) []V {
var zero V
plucked := make([]V, len(items), cap(items))
for i, item := range items {
if v, err := AnyGet[V](item, key); err == nil {
plucked[i] = v
} else {
plucked[i] = zero
}
}
return plucked
}
func MapPluck[K comparable, V any](items []map[K]V, key K) []V {
var zero V
plucked := make([]V, len(items), cap(items))
for i, item := range items {
if v, ok := item[key]; ok {
plucked[i] = v
} else {
plucked[i] = zero
}
}
return plucked
}
func KeyBy[V comparable, K, I any](items []I, key K) map[V]I {
result := make(map[V]I)
for _, item := range items {
if v, err := AnyGet[V](item, key); err == nil {
result[v] = item
}
}
return result
}
func MapKeyBy[K, V comparable](items []map[K]V, key K) map[V]map[K]V {
result := make(map[V]map[K]V)
for _, item := range items {
result[item[key]] = item
}
return result
}
func GroupBy[V comparable, K, I any](items []I, key K) map[V][]I {
result := make(map[V][]I)
for _, item := range items {
if v, err := AnyGet[V](item, key); err == nil {
result[v] = append(result[v], item)
}
}
return result
}
func MapGroupBy[K, V comparable](items []map[K]V, key K) map[V][]map[K]V {
result := make(map[V][]map[K]V)
for _, item := range items {
result[item[key]] = append(result[item[key]], item)
}
return result
}