feat: add min method to Outcome

This commit is contained in:
2025-11-16 09:50:17 +01:00
parent 331fd4d93a
commit e12e954d19
4 changed files with 49 additions and 1 deletions

View File

@@ -0,0 +1,7 @@
use oxidice_lib::dice::*;
fn main() {
let roll_result = Handful::grab(2, 20).roll();
let result = roll_result.clone().min().unwrap();
println!("{} -> {}", roll_result, result);
}

View File

@@ -3,6 +3,6 @@ use crate::*;
impl Die {
pub fn roll(&self) -> u16 {
let mut rng = rand::rng();
rng.random_range(1..=self.sides)
rng.random_range(1..=self.sides) as u16
}
}

View File

@@ -3,4 +3,5 @@ pub mod die_roll;
pub mod handful_grab;
pub mod handful_roll;
pub mod outcome_max;
pub mod outcome_min;
pub mod outcome_sum;

View File

@@ -0,0 +1,40 @@
use crate::*;
fn min_of(values: Vec<u16>) -> Result<Outcome, FailedTo> {
if values.is_empty() {
return Err(FailedTo::ProcessInput);
}
Ok(Outcome::Scalar(u16::MIN)).and_then(|_| {
values
.iter()
.min()
.ok_or(FailedTo::FindMin)
.map(|min| Outcome::Scalar(*min))
})
}
impl Outcome {
pub fn min(self) -> Result<Outcome, FailedTo> {
match self {
Outcome::Scalar(value) => Ok(Outcome::Scalar(value)),
Outcome::List(values) => min_of(values),
}
}
}
#[cfg(test)]
mod unit_tests {
use super::*;
#[test]
fn check_min() {
let roll_result = Handful::grab(2, 20).roll();
let min_result = roll_result.clone().min().unwrap();
match roll_result {
Outcome::List(values) => {
let min = values.iter().min().unwrap();
assert_eq!(min_result, Outcome::Scalar(*min));
}
_ => panic!("result is not a list"),
}
}
}