From 740ce87c3876f39c1aebbabf108d48a2c894c31d Mon Sep 17 00:00:00 2001 From: "chiseok.song" Date: Tue, 16 Jun 2020 15:44:46 +0900 Subject: [PATCH] added function DefaultString, DefaultIfBlank --- stringutils.go | 16 ++++++++++++++++ stringutils_test.go | 30 ++++++++++++++++++++++++++++++ 2 files changed, 46 insertions(+) diff --git a/stringutils.go b/stringutils.go index 5037c45..741bb53 100644 --- a/stringutils.go +++ b/stringutils.go @@ -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 +} diff --git a/stringutils_test.go b/stringutils_test.go index dae9313..76ef753 100644 --- a/stringutils_test.go +++ b/stringutils_test.go @@ -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 +}