Last active
October 13, 2023 20:27
-
-
Save tgaeta/e5212ddb3ac70e01b49b460d7c8a3062 to your computer and use it in GitHub Desktop.
99bottles.rs
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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