-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathslice.go
78 lines (70 loc) · 1.95 KB
/
slice.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
package fragments
import (
"github.com/shousper/go-funcy/model"
. "github.com/dave/jennifer/jen"
)
// SliceOf produces a slice type for the given types
//
// type SliceOfT []T
//
func SliceOf(f *File, m model.Model) {
f.Commentf("%s is a string slice of %s", m.Slice.Name, m.Type)
f.Type().Id(m.Slice.Name).
Index().Add(m.TypeCode())
}
// SliceOfAsMap produces a map from a slice grouping by its defined unique ID
//
// func (s SliceOfT) AsMap() MapOfT {
// result := make(MapOfT)
// for _, value := range s {
// result[value.K] = append(result[value.K], value)
// }
// return result
// }
//
func SliceOfAsMap(f *File, m model.Model) {
outType := Map(m.Map.Key.Type.AsCode()).Add(m.TypeCode())
f.Commentf("AsMap maps slice values by %s", m.Map.Key.Accessor)
f.Func().
Params(Id("s").Id(m.Slice.Name)).
Id("AsMap").
Params().
Add(outType).
Block(
Id("result").Op(":=").Make(outType),
For(List(Id("_"), Id("value")).Op(":=").Range().Id("s")).Block(
Id("result").Index(Id("value").Dot(m.Map.Key.Accessor)).Op("=").Id("value"),
),
Return(Id("result")),
)
}
// SliceOfGroupBys produce a maps of slice values grouped by a field value
//
// func (s SliceOfT) GroupByF() map[J][]T {
// result := make(map[J][]T)
// for _, value := range s {
// result[value.F] = append(result[value.F], value)
// }
// return result
// }
//
func SliceOfGroupBys(f *File, m model.Model) {
for _, g := range m.GroupBys {
fnName := "GroupBy" + g.Name
outType := Map(g.Type.AsCode()).Index().Add(m.TypeCode())
mappedField := Id("result").Index(Id("value").Dot(g.Accessor))
f.Commentf("%s groups slice values by %s", fnName, g.Accessor)
f.Func().
Params(Id("s").Id(m.Slice.Name)).
Id(fnName).
Params().
Add(outType).
Block(
Id("result").Op(":=").Make(outType),
For(List(Id("_"), Id("value")).Op(":=").Range().Id("s")).Block(
Add(mappedField).Op("=").Append(mappedField, Id("value")),
),
Return(Id("result")),
)
}
}