From 1688b2acc286f98fed74eac26ec048005d10fd44 Mon Sep 17 00:00:00 2001 From: Kate Korsaro Date: Sun, 16 Nov 2025 09:30:22 +0100 Subject: [PATCH] feat: add method max to Outcome --- .../examples/roll_d20_with_advantage.rs | 7 ++++ 01.workspace/oxidice_lib/src/imp/mod.rs | 1 + .../oxidice_lib/src/imp/outcome_max.rs | 41 +++++++++++++++++++ 01.workspace/oxidice_lib/src/str/failed_to.rs | 1 + 4 files changed, 50 insertions(+) create mode 100644 01.workspace/oxidice_lib/examples/roll_d20_with_advantage.rs create mode 100644 01.workspace/oxidice_lib/src/imp/outcome_max.rs diff --git a/01.workspace/oxidice_lib/examples/roll_d20_with_advantage.rs b/01.workspace/oxidice_lib/examples/roll_d20_with_advantage.rs new file mode 100644 index 0000000..a519ef5 --- /dev/null +++ b/01.workspace/oxidice_lib/examples/roll_d20_with_advantage.rs @@ -0,0 +1,7 @@ +use oxidice_lib::dice::*; + +fn main() { + let roll_result = Handful::grab(2, 20).roll(); + let result = roll_result.clone().max().unwrap(); + println!("{} -> {}", roll_result, result); +} diff --git a/01.workspace/oxidice_lib/src/imp/mod.rs b/01.workspace/oxidice_lib/src/imp/mod.rs index c75e913..99a175a 100644 --- a/01.workspace/oxidice_lib/src/imp/mod.rs +++ b/01.workspace/oxidice_lib/src/imp/mod.rs @@ -2,4 +2,5 @@ pub mod die_new; pub mod die_roll; pub mod handful_grab; pub mod handful_roll; +pub mod outcome_max; pub mod outcome_sum; diff --git a/01.workspace/oxidice_lib/src/imp/outcome_max.rs b/01.workspace/oxidice_lib/src/imp/outcome_max.rs new file mode 100644 index 0000000..f1b2baa --- /dev/null +++ b/01.workspace/oxidice_lib/src/imp/outcome_max.rs @@ -0,0 +1,41 @@ +use crate::*; + +fn max_of(values: Vec) -> Result { + if values.is_empty() { + return Err(FailedTo::ProcessInput); + } + let ret = Ok(Outcome::Scalar(u16::MAX)); + ret.and_then(|_| { + values + .iter() + .max() + .ok_or(FailedTo::FindMin) + .map(|min| Outcome::Scalar(*min)) + }) +} + +impl Outcome { + pub fn max(self) -> Result { + match self { + Outcome::Scalar(value) => Ok(Outcome::Scalar(value)), + Outcome::List(values) => max_of(values), + } + } +} + +#[cfg(test)] +mod unit_tests { + use super::*; + #[test] + fn check_max() { + let outcome = Handful::grab(2, 20).roll(); + let max = outcome.clone().max().unwrap(); + match outcome { + Outcome::List(values) => { + let expected_max = values.iter().max().unwrap(); + assert_eq!(max, Outcome::Scalar(*expected_max)); + } + _ => panic!("outcome is not a list"), + } + } +} diff --git a/01.workspace/oxidice_lib/src/str/failed_to.rs b/01.workspace/oxidice_lib/src/str/failed_to.rs index a408565..5a10d3c 100644 --- a/01.workspace/oxidice_lib/src/str/failed_to.rs +++ b/01.workspace/oxidice_lib/src/str/failed_to.rs @@ -4,6 +4,7 @@ #[derive(Debug, PartialEq, PartialOrd, Eq, Ord, Clone, Copy, Hash)] pub enum E { + FindMin, ProcessInput, SumValues, }