-
-
Notifications
You must be signed in to change notification settings - Fork 1
/
finders.go
80 lines (64 loc) · 1.39 KB
/
finders.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
package hype
func ByType[T Node](nodes Nodes) []T {
var res []T
for _, t := range nodes {
if x, ok := t.(T); ok {
res = append(res, x)
}
res = append(res, ByType[T](t.Children())...)
}
return res
}
func ByAttrs(nodes Nodes, query map[string]string) []AttrNode {
var res []AttrNode
for _, n := range nodes {
t, ok := n.(AttrNode)
if ok {
ta := t.Attrs()
if AttrMatches(ta, query) {
res = append(res, t)
}
}
res = append(res, ByAttrs(n.Children(), query)...)
}
return res
}
func ByAtom[T ~string](nodes Nodes, want ...T) []AtomableNode {
var res []AtomableNode
for _, n := range nodes {
an, ok := n.(AtomableNode)
if !ok {
res = append(res, ByAtom(n.Children(), want...)...)
continue
}
for _, w := range want {
if an.Atom().String() == string(w) {
res = append(res, an)
break
}
}
res = append(res, ByAtom(n.Children(), want...)...)
}
return res
}
func FirstByType[T Node](nodes Nodes) (T, bool) {
res := ByType[T](nodes)
if len(res) == 0 {
return *new(T), false
}
return res[0], true
}
func FirstByAttrs(nodes Nodes, query map[string]string) (AttrNode, bool) {
res := ByAttrs(nodes, query)
if len(res) == 0 {
return nil, false
}
return res[0], true
}
func FirstByAtom[T ~string](nodes Nodes, want ...T) (AtomableNode, bool) {
res := ByAtom(nodes, want...)
if len(res) == 0 {
return nil, false
}
return res[0], true
}