-
Notifications
You must be signed in to change notification settings - Fork 1
/
loop.go
94 lines (75 loc) · 1.82 KB
/
loop.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
package htmx
// RangeLoop is a loop control structure.
type RangeLoop interface {
// Filter loops and filters the content.
Filter(f func(int) bool) RangeLoop
// Map loops and maps the content.
Map(f func(int) Node) RangeLoop
// Group returns the nodes as a group.
Group() Node
}
type rangeLoop struct {
nodes []Node
src []Node
}
// Range loops over the content.
func Range(nodes ...Node) RangeLoop {
return &rangeLoop{nodes: []Node{}, src: nodes}
}
// Group returns the nodes as a group.
func (r *rangeLoop) Group() Node {
return Group(r.nodes...)
}
// Filter loops and slices the content.
func (r *rangeLoop) Filter(f func(int) bool) RangeLoop {
for i := range r.src {
if f(i) {
r.nodes = append(r.nodes, r.src[i])
}
}
return r
}
// Map loops and maps the content.
func (r *rangeLoop) Map(f func(int) Node) RangeLoop {
for i := range r.src {
r.nodes[i] = f(i)
}
return r
}
// Filter loops and filters the content.
func Filter(f func(n Node) bool, children ...Node) []Node {
var nodes []Node
for i := 0; i < len(children); i++ {
if f(children[i]) {
nodes = append(nodes, children[i])
}
}
return nodes
}
// Map is using a map to transform into htmx nodes.
func Map[T1 comparable, T2 any](m map[T1]T2, f func(T1, T2) Node) Nodes {
nodes := make([]Node, 0, len(m))
for k, v := range m {
nodes = append(nodes, f(k, v))
}
return nodes
}
// Reduce reduces the content to a single node.
func Reduce(f func(prev Node, next Node) Node, children ...Node) Node {
if len(children) == 0 {
return nil
}
node := children[0]
for _, n := range children[1:] {
node = f(node, n)
}
return node
}
// ForEach loops over the content.
func ForEach[S ~[]E, E comparable](s S, f func(E, int) Node) Nodes {
nodes := make([]Node, 0, len(s))
for i, e := range s {
nodes = append(nodes, f(e, i))
}
return nodes
}