Skip to content

Commit 2eb9dc0

Browse files
committed
feat: scale_to_target that considers different ways to scale
1 parent 81d9470 commit 2eb9dc0

1 file changed

Lines changed: 39 additions & 2 deletions

File tree

src/scale.rs

Lines changed: 39 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -23,8 +23,6 @@ pub enum ScaleError {
2323
impl Recipe {
2424
/// Scale a recipe
2525
///
26-
/// Note that this returns a [`ScaledRecipe`] wich doesn't implement this
27-
/// method. A recipe can only be scaled once.
2826
pub fn scale(&mut self, factor: f64, converter: &Converter) {
2927
let scale_quantity = |q: &mut Quantity| {
3028
if q.scalable {
@@ -105,6 +103,45 @@ impl Recipe {
105103
Ok(())
106104
}
107105

106+
/// Scale to a target value with optional unit
107+
///
108+
/// This function intelligently chooses the appropriate scaling method:
109+
/// - If `target_unit` is `Some("servings")`, scales by servings
110+
/// - If `target_unit` is `Some(other_unit)`, scales by yield with that unit
111+
/// - If `target_unit` is `None`, applies direct scaling factor
112+
///
113+
/// # Arguments
114+
/// - `target_value` - The target value (servings count, yield amount, or scaling factor)
115+
/// - `target_unit` - Optional unit ("servings" for servings-based, other for yield-based, None for direct factor)
116+
/// - `converter` - Unit converter for fitting quantities
117+
///
118+
/// # Returns
119+
/// - `Ok(())` on successful scaling
120+
/// - `Err(ScaleError)` if scaling cannot be performed
121+
pub fn scale_to_target(
122+
&mut self,
123+
target_value: f64,
124+
target_unit: Option<&str>,
125+
converter: &Converter,
126+
) -> Result<(), ScaleError> {
127+
match target_unit {
128+
Some("servings") | Some("serving") => {
129+
// Scale by servings - convert f64 to u32
130+
let servings = target_value.round() as u32;
131+
self.scale_to_servings(servings, converter)
132+
}
133+
Some(unit) => {
134+
// Scale by yield with the specified unit
135+
self.scale_to_yield(target_value, unit, converter)
136+
}
137+
None => {
138+
// Direct scaling factor
139+
self.scale(target_value, converter);
140+
Ok(())
141+
}
142+
}
143+
}
144+
108145
/// Scale to a specific yield amount with unit
109146
///
110147
/// - `target_value` is the wanted yield amount

0 commit comments

Comments
 (0)