Skip to content

Commit 8267b47

Browse files
committed
format util
1 parent 81c29c0 commit 8267b47

File tree

2 files changed

+57
-0
lines changed

2 files changed

+57
-0
lines changed

pkg/util/format.go

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
package util
2+
3+
import "strings"
4+
5+
// OrDash returns the string if non-empty, otherwise returns "-".
6+
func OrDash(s string) string {
7+
if s == "" {
8+
return "-"
9+
}
10+
return s
11+
}
12+
13+
// FirstOrDash returns the first non-empty string from the provided items.
14+
// If all items are empty, it returns "-".
15+
func FirstOrDash(items ...string) string {
16+
for _, item := range items {
17+
if item != "" {
18+
return item
19+
}
20+
}
21+
return "-"
22+
}
23+
24+
// JoinOrDash joins the provided strings with ", " as separator.
25+
// If no items are provided, it returns "-".
26+
func JoinOrDash(items ...string) string {
27+
if len(items) == 0 {
28+
return "-"
29+
}
30+
return strings.Join(items, ", ")
31+
}

pkg/util/format_test.go

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
package util
2+
3+
import (
4+
"testing"
5+
6+
"github.com/stretchr/testify/assert"
7+
)
8+
9+
func TestOrDash(t *testing.T) {
10+
assert.Equal(t, "hello", OrDash("hello"))
11+
assert.Equal(t, "-", OrDash(""))
12+
}
13+
14+
func TestFirstOrDash(t *testing.T) {
15+
assert.Equal(t, "first", FirstOrDash("first", "second", "third"))
16+
assert.Equal(t, "second", FirstOrDash("", "second", "third"))
17+
assert.Equal(t, "third", FirstOrDash("", "", "third"))
18+
assert.Equal(t, "-", FirstOrDash("", "", ""))
19+
assert.Equal(t, "-", FirstOrDash())
20+
}
21+
22+
func TestJoinOrDash(t *testing.T) {
23+
assert.Equal(t, "a, b, c", JoinOrDash("a", "b", "c"))
24+
assert.Equal(t, "a", JoinOrDash("a"))
25+
assert.Equal(t, "-", JoinOrDash())
26+
}

0 commit comments

Comments
 (0)