From 0658b6a066e0a24fc729b30aa6938e516f070583 Mon Sep 17 00:00:00 2001 From: Dmitry Kokorin Date: Wed, 2 Mar 2016 11:03:20 +0300 Subject: [PATCH] beer_song: iteration 2 --- cpp/beer-song/beer_song.cpp | 56 ++++++++++++++++++++----------------- 1 file changed, 31 insertions(+), 25 deletions(-) diff --git a/cpp/beer-song/beer_song.cpp b/cpp/beer-song/beer_song.cpp index 9b084ea..106a62d 100644 --- a/cpp/beer-song/beer_song.cpp +++ b/cpp/beer-song/beer_song.cpp @@ -1,51 +1,57 @@ #include "beer_song.h" +#include #include -#include namespace beer { using namespace std; +namespace { + +string count_bottles(int count) +{ + if (0 == count) + return "no more bottles"; + + if (1 == count) + return "1 bottle"; + + return to_string(count) + " bottles"; +}; + +void capitalize_first(string &str) +{ + assert(!str.empty()); + str.front() = toupper(str.front()); +}; + +} + string verse(int index) { - auto count_str = [](int count) -> string { - - if (0 == count) - return "no more bottles"; - - if (1 == count) - return "1 bottle"; - - ostringstream oss; - oss << count << " bottles"; - - return oss.str(); - }; - - auto capitalize_first = [](const string &str) -> string { - - string result = str; - result.front() = toupper(result.front()); - return result; - }; - - return capitalize_first(count_str(index)) + string result = count_bottles(index) + " of beer on the wall, " - + count_str(index) + + count_bottles(index) + " of beer.\n" + (index ? string("Take ") + (index == 1 ? "it" : "one") + " down and pass it around, " : string("Go to the store and buy some more, ")) - + count_str(index ? index - 1 : 99) + + count_bottles(index ? index - 1 : 99) + " of beer on the wall.\n"; + + capitalize_first(result); + + return result; } string sing(int from_index, int to_index) { string result; + assert(from_index >= to_index); + for (int i = from_index; i >= to_index; --i) { result += (i == from_index ? "" : "\n");