exercism/go/beer-song/beer.go

67 lines
1.3 KiB
Go

package beer
import (
"errors"
"strconv"
"strings"
)
// buildBase builds the basic "x bottle(s) of beer"
func buildBase(num int) string {
var ret string
if num == 0 {
ret = "No more"
} else {
ret = strconv.Itoa(num)
}
ret += " bottle"
if num != 1 {
ret += "s"
}
ret += " of beer"
return ret
}
// Verse generates a single verse
func Verse(num int) (string, error) {
var ret string
if num > 99 || num < 0 {
return "", errors.New("Invalid verse requested")
}
ret += buildBase(num) + " on the wall, " + strings.ToLower(buildBase(num)) + ".\n"
if num == 0 {
ret += "Go to the store and buy some more, " + buildBase(99) + " on the wall.\n"
} else {
ret += "Take "
if num == 1 {
ret += "it "
} else {
ret += "one "
}
ret += "down and pass it around, " + strings.ToLower(buildBase(num-1)) + " on the wall.\n"
}
return ret, nil
}
// Verses generates all verses starting at 'st' and going to 'end'
func Verses(st, end int) (string, error) {
if st < end {
return "", errors.New("Start less than stop")
}
var r, ret string
var err error
for i := st; i >= end; i-- {
if r, err = Verse(i); err != nil {
return "", err
}
ret += r + "\n"
}
return ret, nil
}
// Song generates the entire song (all 100 verses)
func Song() string {
r, _ := Verses(99, 0)
return r
}