Skip to content

Commit

Permalink
Add list function the create list of strings
Browse files Browse the repository at this point in the history
Add a function to create a human style list of strings, where a comma separates
each entry and the last one add an additional "and" to the text.
  • Loading branch information
HeavyWombat committed Oct 2, 2019
1 parent 8b8c5ed commit ee9f873
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 1 deletion.
17 changes: 17 additions & 0 deletions text.go
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ Package text contains convenience functions for creating strings
package text

import (
"bytes"
"fmt"
"math/rand"
"strconv"
Expand Down Expand Up @@ -119,3 +120,19 @@ func Plural(amount int, text ...string) string {
return fmt.Sprintf("%s %s", number, text[1])
}
}

// List creates a list of the string entries with commas and an ending "and"
func List(list []string) string {
var buf bytes.Buffer
for idx, entry := range list {
fmt.Fprint(&buf, entry)

if idx < len(list)-2 {
fmt.Fprint(&buf, ", ")
} else if idx < len(list)-1 {
fmt.Fprint(&buf, ", and ")
}
}

return buf.String()
}
9 changes: 8 additions & 1 deletion text_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -95,7 +95,7 @@ var _ = Describe("Generate random strings with fixed length", func() {
})
})

Context("creating proper texts", func() {
Context("Creating proper plurals", func() {
It("should return human readable plurals", func() {
Expect(Plural(0, "foobar")).To(BeEquivalentTo("no foobars"))
Expect(Plural(1, "foobar")).To(BeEquivalentTo("one foobar"))
Expand All @@ -117,4 +117,11 @@ var _ = Describe("Generate random strings with fixed length", func() {
Expect(Plural(2, "basis", "bases")).To(BeEquivalentTo("two bases"))
})
})

Context("Creating human readable lists", func() {
It("should create a human readable list of strings", func() {
Expect(List([]string{"one", "two", "three", "four"})).
To(BeEquivalentTo("one, two, three, and four"))
})
})
})

0 comments on commit ee9f873

Please sign in to comment.