Skip to content

Instantly share code, notes, and snippets.

@chase-lambert
Created April 23, 2025 01:05
Show Gist options
  • Select an option

  • Save chase-lambert/d554ecb0537a2dfbb10e9eb1adf8b617 to your computer and use it in GitHub Desktop.

Select an option

Save chase-lambert/d554ecb0537a2dfbb10e9eb1adf8b617 to your computer and use it in GitHub Desktop.

Revisions

  1. chase-lambert created this gist Apr 23, 2025.
    45 changes: 45 additions & 0 deletions calculate_ingredients.rs
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,45 @@
    #[derive(Debug, PartialEq)]
    pub struct Ingredient<'a> {
    pub name: &'a str,
    pub amount: u32,
    }

    impl<'a> Ingredient<'a> {
    fn new(name: &'a str, amount: u32) -> Self {
    Self { name, amount }
    }
    }

    pub fn calculate_ingredients<'a>(
    ingredients: &'a [Ingredient],
    target_servings: u32,
    ) -> Vec<Ingredient<'a>> {
    ingredients
    .iter()
    .map(|ingredient| Ingredient::new(ingredient.name, ingredient.amount * target_servings))
    .collect()
    }

    #[cfg(test)]
    mod tests {
    use super::*;

    #[test]
    fn calculate_ingredients_test() {
    let ingredients = vec![
    Ingredient::new("flour", 200),
    Ingredient::new("sugar", 100),
    Ingredient::new("eggs", 2),
    ];
    let target_servings = 3;

    let result = calculate_ingredients(&ingredients, target_servings);
    let expected = vec![
    Ingredient::new("flour", 600),
    Ingredient::new("sugar", 300),
    Ingredient::new("eggs", 6),
    ];

    assert_eq!(result, expected);
    }
    }