Skip to content

Instantly share code, notes, and snippets.

@pkoch
Created August 25, 2019 14:11
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 pkoch/2c938d86ae4824a003e17d885228d3fd to your computer and use it in GitHub Desktop.
Save pkoch/2c938d86ae4824a003e17d885228d3fd to your computer and use it in GitHub Desktop.
pub fn sounder<'a>(div: u32, msg: &'a str) -> impl Fn(u32) -> Option<&'a str>
{
move |n: u32|{
if n % div != 0 {
return None;
};
Some(msg)
}
}
pub trait NonEmptyOr {
fn non_empty_or<'a, 'b: 'a>(self: &'a Self, alternative: &'b Self) -> &'a Self;
}
impl NonEmptyOr for String {
fn non_empty_or<'a, 'b: 'a>(self: &'a Self, alternative: &'b Self) -> &'a Self {
if !self.is_empty() {
return self;
};
alternative
}
}
pub fn raindrops(n: u32) -> String {
[
sounder(3, "Pling"),
sounder(5, "Plang"),
sounder(7, "Plong"),
]
.iter()
.filter_map(|f| f(n))
.collect::<Vec<&str>>()
.concat()
.non_empty_or(&n.to_string())
.to_owned()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment