Skip to content

Commit 2ee2e49

Browse files
authored
Merge pull request #142 from radovskyb/master
Optimizes the *Selection.Text method and reduces allocations.
2 parents 152b1a2 + c0b805c commit 2ee2e49

File tree

1 file changed

+14
-17
lines changed

1 file changed

+14
-17
lines changed

Diff for: property.go

+14-17
Original file line numberDiff line numberDiff line change
@@ -63,9 +63,22 @@ func (s *Selection) Text() string {
6363
var buf bytes.Buffer
6464

6565
// Slightly optimized vs calling Each: no single selection object created
66+
var f func(*html.Node)
67+
f = func(n *html.Node) {
68+
if n.Type == html.TextNode {
69+
// Keep newlines and spaces, like jQuery
70+
buf.WriteString(n.Data)
71+
}
72+
if n.FirstChild != nil {
73+
for c := n.FirstChild; c != nil; c = c.NextSibling {
74+
f(c)
75+
}
76+
}
77+
}
6678
for _, n := range s.Nodes {
67-
buf.WriteString(getNodeText(n))
79+
f(n)
6880
}
81+
6982
return buf.String()
7083
}
7184

@@ -192,22 +205,6 @@ func (s *Selection) ToggleClass(class ...string) *Selection {
192205
return s
193206
}
194207

195-
// Get the specified node's text content.
196-
func getNodeText(node *html.Node) string {
197-
if node.Type == html.TextNode {
198-
// Keep newlines and spaces, like jQuery
199-
return node.Data
200-
} else if node.FirstChild != nil {
201-
var buf bytes.Buffer
202-
for c := node.FirstChild; c != nil; c = c.NextSibling {
203-
buf.WriteString(getNodeText(c))
204-
}
205-
return buf.String()
206-
}
207-
208-
return ""
209-
}
210-
211208
func getAttributePtr(attrName string, n *html.Node) *html.Attribute {
212209
if n == nil {
213210
return nil

0 commit comments

Comments
 (0)