Skip to content

Commit f8e202f

Browse files
committed
crstrings: add LinesSeq
Add a LinesSeq func that behaves like Lines but returns an iterator of strings instead of a slice.
1 parent 7847643 commit f8e202f

File tree

1 file changed

+10
-4
lines changed

1 file changed

+10
-4
lines changed

crstrings/utils.go

Lines changed: 10 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,7 @@ package crstrings
1616

1717
import (
1818
"fmt"
19+
"iter"
1920
"slices"
2021
"strings"
2122
)
@@ -87,15 +88,20 @@ func FilterEmpty(elems []string) []string {
8788

8889
// Lines breaks up the given string into lines.
8990
func Lines(s string) []string {
91+
return slices.Collect(LinesSeq(s))
92+
}
93+
94+
// LinesSeq returns an iterator over the lines of the given string.
95+
func LinesSeq(s string) iter.Seq[string] {
9096
// Remove any trailing newline (to avoid getting an extraneous empty line at
9197
// the end).
9298
s = strings.TrimSuffix(s, "\n")
9399
if s == "" {
94-
// In this case, Split returns a slice with a single empty string (which is
95-
// not what we want).
96-
return nil
100+
// In this case, SplitSeq returns an iterator with a single empty string
101+
// (which is not what we want).
102+
return func(yield func(string) bool) {}
97103
}
98-
return strings.Split(s, "\n")
104+
return strings.SplitSeq(s, "\n")
99105
}
100106

101107
// Indent prepends a string to every line of the given string.

0 commit comments

Comments
 (0)