diff options
Diffstat (limited to 'helpers')
-rw-r--r-- | helpers/general.go | 21 | ||||
-rw-r--r-- | helpers/general_test.go | 26 |
2 files changed, 45 insertions, 2 deletions
diff --git a/helpers/general.go b/helpers/general.go index 76275a6b9..5c3af9712 100644 --- a/helpers/general.go +++ b/helpers/general.go @@ -255,6 +255,27 @@ func SliceToLower(s []string) []string { return l } +// StringSliceToList formats a string slice into a human-readable list. +// It joins the elements of the slice s with commas, using an Oxford comma, +// and precedes the final element with the conjunction c. +func StringSliceToList(s []string, c string) string { + const defaultConjunction = "and" + + if c == "" { + c = defaultConjunction + } + if len(s) == 0 { + return "" + } + if len(s) == 1 { + return s[0] + } + if len(s) == 2 { + return fmt.Sprintf("%s %s %s", s[0], c, s[1]) + } + return fmt.Sprintf("%s, %s %s", strings.Join(s[:len(s)-1], ", "), c, s[len(s)-1]) +} + // IsWhitespace determines if the given rune is whitespace. func IsWhitespace(r rune) bool { return r == ' ' || r == '\t' || r == '\n' || r == '\r' diff --git a/helpers/general_test.go b/helpers/general_test.go index 686e95ded..6d2a78e02 100644 --- a/helpers/general_test.go +++ b/helpers/general_test.go @@ -18,9 +18,8 @@ import ( "strings" "testing" - "github.com/gohugoio/hugo/helpers" - qt "github.com/frankban/quicktest" + "github.com/gohugoio/hugo/helpers" ) func TestResolveMarkup(t *testing.T) { @@ -304,3 +303,26 @@ func BenchmarkUniqueStrings(b *testing.B) { } }) } + +func TestStringSliceToList(t *testing.T) { + for _, tt := range []struct { + slice []string + conjunction string + want string + }{ + {[]string{}, "", ""}, + {[]string{"foo"}, "", "foo"}, + {[]string{"foo"}, "and", "foo"}, + {[]string{"foo", "bar"}, "", "foo and bar"}, + {[]string{"foo", "bar"}, "and", "foo and bar"}, + {[]string{"foo", "bar"}, "or", "foo or bar"}, + {[]string{"foo", "bar", "baz"}, "", "foo, bar, and baz"}, + {[]string{"foo", "bar", "baz"}, "and", "foo, bar, and baz"}, + {[]string{"foo", "bar", "baz"}, "or", "foo, bar, or baz"}, + } { + got := helpers.StringSliceToList(tt.slice, tt.conjunction) + if got != tt.want { + t.Errorf("StringSliceToList() got: %q, want: %q", got, tt.want) + } + } +} |