Skip to content

Instantly share code, notes, and snippets.

@shmolyneaux
Last active October 15, 2019 05:53
Show Gist options
  • Save shmolyneaux/18489fa25040dc8844947834b50bdbe1 to your computer and use it in GitHub Desktop.
Save shmolyneaux/18489fa25040dc8844947834b50bdbe1 to your computer and use it in GitHub Desktop.
Indexing Cat Groups
/// Cats, groups of cats, and cat ages obfuscate business objects
/// for an actual problem trying to be solved
use std::collections::HashMap;
struct Cat {
age: u8
}
struct CatGroup {
cats: Vec<Cat>,
cat_index: HashMap<u8, Vec<usize>>
}
impl CatGroup {
fn new() -> CatGroup {
CatGroup{ cats: Vec::new(), cat_index: HashMap::new()}
}
fn add_cat(&mut self, cat: Cat) {
self.cat_index
.entry(cat.age)
.or_insert(Vec::new())
.push(self.cats.len());
self.cats.push(cat);
}
fn iter(&self) -> impl Iterator<Item = &Cat> {
self.cats.iter()
}
fn iter_cats_with_age<'a>(&'a self, age: u8) -> Box<dyn Iterator<Item = &Cat> + 'a> {
match self.cat_index.get(&age) {
Some(v) => Box::new(v.iter().map(move |idx| self.cats.get(*idx).unwrap())),
None => Box::new(std::iter::empty())
}
}
}
fn main() {
let mut cats = CatGroup::new();
cats.add_cat(Cat{age: 4});
cats.add_cat(Cat{age: 4});
cats.add_cat(Cat{age: 5});
cats.add_cat(Cat{age: 6});
cats.add_cat(Cat{age: 4});
println!("Four year old cats:");
for cat in cats.iter_cats_with_age(4) {
println!("Cat with age {}", cat.age);
}
println!("All Cats:");
for cat in cats.iter() {
println!("Cat with age {}", cat.age);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment