From e22b1b7c916e4339fda61c6a91f6f1f10778894a Mon Sep 17 00:00:00 2001 From: Dimitri Sokolyuk Date: Thu, 25 Aug 2016 16:47:37 +0200 Subject: wip --- go/food-chain/food_chain.go | 72 ++++++++++++++++++++++++++++++++++++++++++--- 1 file changed, 68 insertions(+), 4 deletions(-) diff --git a/go/food-chain/food_chain.go b/go/food-chain/food_chain.go index ce651a8..2d67835 100644 --- a/go/food-chain/food_chain.go +++ b/go/food-chain/food_chain.go @@ -1,15 +1,79 @@ package foodchain +import ( + "bytes" + "strings" + "text/template" +) + const testVersion = 2 +const lyrics = `I know an old lady who swallowed a {{.Animal}}. +{{- if eq .Animal "fly"}} +{{- else 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 {{if eq .B "spider" -}} +spider that wriggled and jiggled and tickled inside her{{else -}} +{{.B}}{{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{ + //"horse", "cow", "goat", "dog", "cat", "bird", "spider", "fly", + "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 { - return "" + buf := new(bytes.Buffer) + pairs := []pair{} + if n < 8 { + 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(a, b int) string { - return "" +func Verses(from, to int) string { + buf := make([]string, to-from) + for i := 0; i < to-from; i++ { + buf[i] = Verse(i + 1) + } + return strings.Join(buf, "\n\n") } func Song() string { - return "" + return Verses(1, 8) } -- cgit v1.2.3