Skip to content

Commit

Permalink
✨ feat: strutil - add new func BlankOr, ZeroOr for check and return v…
Browse files Browse the repository at this point in the history
…alue
  • Loading branch information
inhere committed Jul 24, 2023
1 parent ecbbbc8 commit fbe027e
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 2 deletions.
24 changes: 22 additions & 2 deletions strutil/strutil.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,24 @@ func OrCond(cond bool, s1, s2 string) string {
return s2
}

// OrElse return s OR orVal(new-value) on s is empty
// BlankOr return default value on val is blank, else return val
func BlankOr(val, defVal string) string {
val = strings.TrimSpace(val)
if val != "" {
return val
}
return defVal
}

// ZeroOr return default value on val is zero, else return val. same of OrElse()
func ZeroOr[T ~string](val, defVal T) T {
if val != "" {
return val
}
return defVal
}

// OrElse return default value on val is zero, else return s
func OrElse(s, orVal string) string {
if s != "" {
return s
Expand Down Expand Up @@ -137,7 +154,7 @@ func WrapTag(s, tag string) string {
// substr The substring to search for
// params[0] The offset where to start counting.
// params[1] The maximum length after the specified offset to search for the substring.
func SubstrCount(s string, substr string, params ...uint64) (int, error) {
func SubstrCount(s, substr string, params ...uint64) (int, error) {
larg := len(params)
hasArgs := larg != 0
if hasArgs && larg > 2 {
Expand All @@ -146,9 +163,11 @@ func SubstrCount(s string, substr string, params ...uint64) (int, error) {
if !hasArgs {
return strings.Count(s, substr), nil
}

strlen := len(s)
offset := 0
end := strlen

if hasArgs {
offset = int(params[0])
if larg == 2 {
Expand All @@ -159,6 +178,7 @@ func SubstrCount(s string, substr string, params ...uint64) (int, error) {
end = strlen
}
}

s = string([]rune(s)[offset:end])
return strings.Count(s, substr), nil
}
9 changes: 9 additions & 0 deletions strutil/strutil_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,15 @@ func TestValid(t *testing.T) {
is.Eq("cd", strutil.OrElse("", "cd"))
is.Eq("ab", strutil.OrElse("ab", "cd"))

is.Eq(" ", strutil.ZeroOr(" ", "cd"))
is.Eq("cd", strutil.ZeroOr("", "cd"))
is.Eq("ab", strutil.ZeroOr("ab", "cd"))

is.Eq("cd", strutil.BlankOr("", "cd"))
is.Eq("cd", strutil.BlankOr(" ", "cd"))
is.Eq("ab", strutil.BlankOr("ab", "cd"))
is.Eq("ab", strutil.BlankOr(" ab ", "cd"))

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

Expand Down

0 comments on commit fbe027e

Please sign in to comment.