Skip to content

Commit

Permalink
👔 up(str): update some str value get func
Browse files Browse the repository at this point in the history
  • Loading branch information
inhere committed Feb 1, 2023
1 parent 2e7aa63 commit 676fe4e
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 0 deletions.
16 changes: 16 additions & 0 deletions strutil/strutil.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,14 @@ import (
"text/template"
)

// OrCond return s1 on cond is True, OR return s2.
func OrCond(cond bool, s1, s2 string) string {
if cond {
return s1
}
return s2
}

// OrElse return s OR nv(new-value) on s is empty
func OrElse(s, newVal string) string {
if s != "" {
Expand All @@ -18,6 +26,14 @@ func OrElse(s, newVal string) string {
return newVal
}

// OrHandle return fn(s) on s is not empty.
func OrHandle(s string, fn func(s string) string) string {
if s != "" {
return fn(s)
}
return s
}

// Valid return first not empty element.
func Valid(ss ...string) string {
for _, s := range ss {
Expand Down
6 changes: 6 additions & 0 deletions strutil/strutil_test.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package strutil_test

import (
"strings"
"testing"

"github.com/gookit/goutil/strutil"
Expand All @@ -21,6 +22,11 @@ func TestValid(t *testing.T) {
is.Eq("cd", strutil.Valid("", "cd"))
is.Eq("cd", strutil.OrElse("", "cd"))
is.Eq("ab", strutil.OrElse("ab", "cd"))

is.Eq("ab", strutil.OrCond(true, "ab", "cd"))
is.Eq("cd", strutil.OrCond(false, "ab", "cd"))

is.Eq("ab", strutil.OrHandle(" ab ", strings.TrimSpace))
}

func TestRenderTemplate(t *testing.T) {
Expand Down

0 comments on commit 676fe4e

Please sign in to comment.