-
Notifications
You must be signed in to change notification settings - Fork 0
/
slice_holder.go
77 lines (66 loc) · 1.46 KB
/
slice_holder.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
package zinc
type SliceHolder interface {
SlicePtr() any
Aggregate()
}
// associated
type associatedSliceHolder[K comparable, V any] struct {
slice []V
dest *map[K]V
aggregator func(V) (K, bool)
}
func AssociatedDest[K comparable, V any](dest *map[K]V, aggregator func(V) (K, bool)) SliceHolder {
return &associatedSliceHolder[K, V]{
slice: nil,
dest: dest,
aggregator: aggregator,
}
}
func (h *associatedSliceHolder[K, V]) SlicePtr() any {
return &h.slice
}
func (h *associatedSliceHolder[K, V]) Aggregate() {
if len(h.slice) <= 0 || h.dest == nil || h.aggregator == nil {
return
}
m := map[K]V{}
for _, elem := range h.slice {
if k, ok := h.aggregator(elem); ok {
m[k] = elem
}
}
*h.dest = m
}
// grouped
type groupedSliceHolder[K comparable, V any] struct {
slice []V
dest *map[K][]V
aggregator func(V) (K, bool)
}
func GroupedDest[K comparable, V any](dest *map[K][]V, aggregator func(V) (K, bool)) SliceHolder {
return &groupedSliceHolder[K, V]{
slice: nil,
dest: dest,
aggregator: aggregator,
}
}
func (h *groupedSliceHolder[K, V]) SlicePtr() any {
return &h.slice
}
func (h *groupedSliceHolder[K, V]) Aggregate() {
if len(h.slice) <= 0 || h.dest == nil || h.aggregator == nil {
return
}
m := map[K][]V{}
for _, elem := range h.slice {
if k, ok := h.aggregator(elem); ok {
g, gOk := m[k]
if gOk {
m[k] = append(g, elem)
} else {
m[k] = []V{elem}
}
}
}
*h.dest = m
}