summaryrefslogtreecommitdiff
path: root/go/food-chain/food_chain.go
blob: 403396dddbd78469e44182b3aebad48a24530a79 (plain)
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
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
package foodchain

import (
	"bytes"
	"strings"
	"text/template"
)

const testVersion = 2

const lyrics = `I know an old lady who swallowed a {{.Animal}}.
{{- if eq .Animal "spider"}}
It wriggled and jiggled and tickled inside her.
{{- else if eq .Animal "bird"}}
How absurd to swallow a bird!
{{- else if eq .Animal "cat"}}
Imagine that, to swallow a cat!
{{- else if eq .Animal "dog"}}
What a hog, to swallow a dog!
{{- else if eq .Animal "goat"}}
Just opened her throat and swallowed a goat!
{{- else if eq .Animal "cow"}}
I don't know how she swallowed a cow!
{{- end}}
{{- range .Animals}}
She swallowed the {{.A}} to catch the {{.B}}{{if eq .B "spider"}} that wriggled and jiggled and tickled inside her{{end}}.
{{- end}}
{{- if eq .Animal "horse"}}
She's dead, of course!
{{- else}}
I don't know why she swallowed the fly. Perhaps she'll die.
{{- end}}`

var animals = []string{
	"fly", "spider", "bird", "cat", "dog", "goat", "cow", "horse",
}

type pair struct {
	A, B string
}

type verse struct {
	Animal  string
	Animals []pair
}

var tmpl = template.Must(template.New("song").Parse(lyrics))

func Verse(n int) string {
	buf := new(bytes.Buffer)
	pairs := []pair{}
	if n < len(animals) {
		for i := 0; i < n-1; i++ {
			p := pair{A: animals[i+1], B: animals[i]}
			pairs = append([]pair{p}, pairs...)
		}
	}
	v := verse{
		Animal:  animals[n-1],
		Animals: pairs,
	}
	tmpl.Execute(buf, v)
	return buf.String()
}

func Verses(from, to int) string {
	buf := make([]string, to-from+1)
	for i := 0; i < to-from+1; i++ {
		buf[i] = Verse(i + 1)
	}
	return strings.Join(buf, "\n\n")
}

func Song() string {
	return Verses(1, 8)
}