Add rudimentary ingredient parsing and merging

This commit is contained in:
Matteo Settenvini 2022-08-12 16:30:37 +02:00
parent e69d8fc24c
commit 7025ee9e3a
Signed by: matteo
GPG key ID: 8576CC1AD97D42DF
2 changed files with 191 additions and 11 deletions

View file

@ -85,15 +85,42 @@ where
Ok(ingredients.into_iter().flatten().collect())
}
fn merge_ingredients(mut ingredients: Vec<(Ingredient, String)>) -> Vec<(Ingredient, String)> {
ingredients.sort();
fn merge_ingredients(mut ingredients: Vec<(Ingredient, String)>) -> Vec<(Ingredient, Vec<String>)> {
if ingredients.is_empty() {
return vec![];
}
// TODO actual merging
// Prime merged_ingredients with the first ingredient in sorted order.
ingredients.sort_by(|(a, _), (b, _)| {
a.name.cmp(&b.name).then_with(|| {
// inefficient, but not so bad for now
a.unit.to_string().cmp(&b.unit.to_string())
})
});
let (mut merged_ingredients, ingredients): (Vec<(Ingredient, Vec<String>)>, _) = {
let v = ingredients.split_off(1);
(
ingredients.into_iter().map(|(i, s)| (i, vec![s])).collect(),
v,
)
};
ingredients
for (ingredient, recipe) in ingredients {
// If it can be summed to the last item of merged_ingredients, do it;
// else append it
let (last_i, last_rs) = merged_ingredients.last_mut().unwrap();
if last_i.name == ingredient.name && last_i.unit == ingredient.unit {
last_i.amount += ingredient.amount;
last_rs.push(recipe);
} else {
merged_ingredients.push((ingredient, vec![recipe]));
}
}
merged_ingredients
}
fn prepare_grocery_list(ingredients: &Vec<(Ingredient, String)>) -> Result<String> {
fn prepare_grocery_list(ingredients: &Vec<(Ingredient, Vec<String>)>) -> Result<String> {
let mut out = String::new();
use std::fmt::Write;
@ -103,9 +130,11 @@ fn prepare_grocery_list(ingredients: &Vec<(Ingredient, String)>) -> Result<Strin
chrono::Local::now().format("%Y-%m-%d").to_string()
)?;
writeln!(out)?; // leave an empty line
for ingredient in ingredients {
let ingredient_s = ingredient.0 .0.as_str();
writeln!(out, "- [ ] {} ({})", ingredient_s, ingredient.1)?;
for (ingredient, recipes) in ingredients {
writeln!(out, "- [ ] {}", ingredient)?;
for recipe in recipes {
writeln!(out, " * {}", recipe)?;
}
}
Ok(out)