File tree Expand file tree Collapse file tree 2 files changed +36
-11
lines changed Expand file tree Collapse file tree 2 files changed +36
-11
lines changed Original file line number Diff line number Diff line change @@ -123,16 +123,26 @@ func Plural(amount int, text ...string) string {
123123
124124// List creates a list of the string entries with commas and an ending "and"
125125func List (list []string ) string {
126- var buf bytes.Buffer
127- for idx , entry := range list {
128- fmt .Fprint (& buf , entry )
129-
130- if idx < len (list )- 2 {
131- fmt .Fprint (& buf , ", " )
132- } else if idx < len (list )- 1 {
133- fmt .Fprint (& buf , ", and " )
126+ switch len (list ) {
127+ case 1 :
128+ return list [0 ]
129+
130+ case 2 :
131+ return fmt .Sprintf ("%s and %s" , list [0 ], list [1 ])
132+
133+ default :
134+ var buf bytes.Buffer
135+ for idx , entry := range list {
136+ fmt .Fprint (& buf , entry )
137+
138+ if idx < len (list )- 2 {
139+ fmt .Fprint (& buf , ", " )
140+
141+ } else if idx < len (list )- 1 {
142+ fmt .Fprint (& buf , ", and " )
143+ }
134144 }
135- }
136145
137- return buf .String ()
146+ return buf .String ()
147+ }
138148}
Original file line number Diff line number Diff line change @@ -119,7 +119,22 @@ var _ = Describe("Generate random strings with fixed length", func() {
119119 })
120120
121121 Context ("Creating human readable lists" , func () {
122- It ("should create a human readable list of strings" , func () {
122+ It ("should create a human readable list of no strings" , func () {
123+ Expect (List ([]string {})).
124+ To (BeEquivalentTo ("" ))
125+ })
126+
127+ It ("should create a human readable list of one strings" , func () {
128+ Expect (List ([]string {"one" })).
129+ To (BeEquivalentTo ("one" ))
130+ })
131+
132+ It ("should create a human readable list of two strings" , func () {
133+ Expect (List ([]string {"one" , "two" })).
134+ To (BeEquivalentTo ("one and two" ))
135+ })
136+
137+ It ("should create a human readable list of multiple strings" , func () {
123138 Expect (List ([]string {"one" , "two" , "three" , "four" })).
124139 To (BeEquivalentTo ("one, two, three, and four" ))
125140 })
You can’t perform that action at this time.
0 commit comments