Skip to content

Commit

Permalink
Merge pull request #28 from misoboy/master
Browse files Browse the repository at this point in the history
added function DefaultString, DefaultIfBlank
  • Loading branch information
technosophos committed Jun 16, 2020
2 parents 41ac869 + 740ce87 commit 864fea7
Show file tree
Hide file tree
Showing 2 changed files with 46 additions and 0 deletions.
16 changes: 16 additions & 0 deletions stringutils.go
Original file line number Diff line number Diff line change
Expand Up @@ -222,3 +222,19 @@ func IndexOf(str string, sub string, start int) int {
func IsEmpty(str string) bool {
return len(str) == 0
}

// Returns either the passed in string, or if the string is empty, the value of defaultStr.
func DefaultString(str string, defaultStr string) string {
if IsEmpty(str) {
return defaultStr
}
return str
}

// Returns either the passed in string, or if the string is whitespace, empty (""), the value of defaultStr.
func DefaultIfBlank(str string, defaultStr string) string {
if IsBlank(str) {
return defaultStr
}
return str
}
30 changes: 30 additions & 0 deletions stringutils_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -307,3 +307,33 @@ func ExampleIndexOfDifference() {
// 0
// 2
}

func ExampleDefaultString() {

out1 := DefaultString("abc", "")
out2 := DefaultString("ab", "c")
out3 := DefaultString("", "abc")

fmt.Println(out1)
fmt.Println(out2)
fmt.Println(out3)
// Output:
// abc
// ab
// abc
}

func ExampleDefaultIfBlank() {

out1 := DefaultIfBlank("", "abc")
out2 := DefaultIfBlank(" ", "abc")
out3 := DefaultIfBlank("ab", "cd")

fmt.Println(out1)
fmt.Println(out2)
fmt.Println(out3)
// Output:
// abc
// abc
// ab
}

0 comments on commit 864fea7

Please sign in to comment.