-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathHumanJoin.go
41 lines (32 loc) · 830 Bytes
/
HumanJoin.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
package main
import "fmt"
func main() {
arr := []string{}
fmt.Println(HumanJoin(arr)) // Should print ''
arr = append(arr, "a")
fmt.Println(HumanJoin(arr)) // Should print 'a'
arr = append(arr, "b")
fmt.Println(HumanJoin(arr)) // Should print 'a and b'
arr = append(arr, "c")
fmt.Println(HumanJoin(arr)) // Should print 'a, b, and c'
arr = append(arr, "d")
fmt.Println(HumanJoin(arr)) // Should print 'a, b, c, and d'
}
func HumanJoin(arr []string) string {
res := ""
arrLen := len(arr)
for i, v := range arr {
res += v
if i != arrLen-1 {
if arrLen > 2 {
res += ", "
} else {
res += " "
}
}
if i == arrLen-2 {
res += "and "
}
}
return res
}