Skip to content

Instantly share code, notes, and snippets.

@tgaeta
Last active October 13, 2023 20:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tgaeta/e5212ddb3ac70e01b49b460d7c8a3062 to your computer and use it in GitHub Desktop.
Save tgaeta/e5212ddb3ac70e01b49b460d7c8a3062 to your computer and use it in GitHub Desktop.
99bottles.rs
impl Bottles {
pub fn song(&self) -> String {
self.verses(99, 0)
}
pub fn verse(&self, n: i32) -> String {
format!("{} {} of beer on the wall, {} {} of beer.\n{}",
self.start(n),
self.pluralization(n),
self.start(n).to_lowercase(),
self.pluralization(n),
self.beer_chore(n)
)
}
pub fn verses(&self, from: i32, to: i32) -> String {
(to..=from).rev().map(|n| self.verse(n)).collect::<Vec<String>>().join("\n")
}
fn pluralization(&self, n: i32) -> &'static str {
if n == 1 {
"bottle"
} else {
"bottles"
}
}
fn pronoun(&self, n: i32) -> &'static str {
if n == 1 {
"it"
} else {
"one"
}
}
fn remaining(&self, n: i32) -> i32 {
n - 1
}
fn start(&self, n: i32) -> String {
if n == 0 {
"No more".to_string()
} else {
n.to_string()
}
}
fn beer_chore(&self, n: i32) -> String {
if n == 0 {
"Go to the store and buy some more, 99 bottles of beer on the wall.\n".to_string()
} else {
format!("Take {} down and pass it around, {} {} of beer on the wall.\n",
self.pronoun(n),
if self.remaining(n) == 0 { "no more".to_string() } else { self.remaining(n).to_string() },
self.pluralization(n - 1)
)
}
}
}
fn main() {
let bottles = Bottles;
println!("{}", bottles.song());
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment