Skip to content

Commit

Permalink
strutil: introduce JoinNonEmpty
Browse files Browse the repository at this point in the history
JoinNonEmpty concatenates non-empty strings with the specified
separator. This overcomes a problem with strings.Join, which
introduces separators for empty strings.
  • Loading branch information
alfonsosanchezbeato authored and mvo5 committed Feb 27, 2023
1 parent c6de284 commit 4d8f4df
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 0 deletions.
15 changes: 15 additions & 0 deletions strutil/strutil.go
Original file line number Diff line number Diff line change
Expand Up @@ -355,3 +355,18 @@ func WordWrapPadded(out io.Writer, text []rune, pad string, termWidth int) error
}
return WordWrap(out, text, indent, indent, termWidth)
}

// JoinNonEmpty concatenates non-empty strings using sep as separator,
// and trimming sep from beginning and end of the strings. This
// overcomes a problem with strings.Join, which will introduce
// separators for empty strings.
func JoinNonEmpty(strs []string, sep string) string {
nonEmpty := make([]string, 0, len(strs))
for _, s := range strs {
s = strings.Trim(s, sep)
if s != "" {
nonEmpty = append(nonEmpty, s)
}
}
return strings.Join(nonEmpty, sep)
}
15 changes: 15 additions & 0 deletions strutil/strutil_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -347,3 +347,18 @@ func (strutilSuite) TestWordWrapPadded(c *check.C) {
c.Check(buf.String(), check.Equals, t.output)
}
}

func (strutilSuite) TestJoinNonEmpty(c *check.C) {
for _, t := range []struct {
in []string
out string
}{
{in: []string{}, out: ""},
{in: []string{"", "bar"}, out: "bar"},
{in: []string{"", " ", "bar"}, out: "bar"},
{in: []string{"foo", "", "bar"}, out: "foo bar"},
{in: []string{" val ", " ", " boo"}, out: "val boo"},
} {
c.Check(strutil.JoinNonEmpty(t.in, " "), check.Equals, t.out)
}
}

0 comments on commit 4d8f4df

Please sign in to comment.