Skip to content

Commit 1b0f02a

Browse files
committed
Fix list function for edge scenarios
The list function did not return correct lists for two entries, because it added an unnecessary comma. Add check for special length in order to create the correct results.
1 parent ee9f873 commit 1b0f02a

File tree

2 files changed

+36
-11
lines changed

2 files changed

+36
-11
lines changed

text.go

Lines changed: 20 additions & 10 deletions
Original file line numberDiff line numberDiff 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"
125125
func 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
}

text_test.go

Lines changed: 16 additions & 1 deletion
Original file line numberDiff line numberDiff 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
})

0 commit comments

Comments
 (0)