feat: add sum method to Outcome

This commit is contained in:
2025-11-16 09:03:58 +01:00
parent 85194b3f0f
commit 8620cc124a
3 changed files with 42 additions and 1 deletions

View File

@@ -2,3 +2,4 @@ pub mod die_new;
pub mod die_roll;
pub mod handful_grab;
pub mod handful_roll;
pub mod outcome_sum;

View File

@@ -0,0 +1,37 @@
use crate::*;
fn sum_of(values: Vec<u16>) -> Result<Outcome, FailedTo> {
if values.is_empty() {
return Ok(Outcome::Scalar(0));
}
let mut ret = Ok(Outcome::Scalar(0));
for value in values {
ret = ret.and_then(|outcome: Outcome| match outcome {
Outcome::List(_) => Err(FailedTo::ProcessInput),
Outcome::Scalar(acc) => acc
.checked_add(value)
.map(|new_acc: u16| Outcome::Scalar(new_acc))
.ok_or(FailedTo::SumValues),
})
}
ret
}
impl Outcome {
pub fn sum(self) -> Result<Outcome, FailedTo> {
match self {
Outcome::Scalar(value) => Ok(Outcome::Scalar(value)),
Outcome::List(values) => sum_of(values),
}
}
}
#[cfg(test)]
mod unit_tests {
use super::*;
#[test]
fn check_sum() {
let outcome = Handful::grab(5, 1).roll().sum();
assert_eq!(outcome, Ok(Outcome::Scalar(5)));
}
}

View File

@@ -3,7 +3,10 @@ use crate::*;
// use std::str::FromStr;
#[derive(Debug, PartialEq, PartialOrd, Eq, Ord, Clone, Copy, Hash)]
pub enum E {}
pub enum E {
ProcessInput,
SumValues,
}
// impl Display for E {
// fn fmt(&self, f: &mut std::fmt::Formatter) -> std::result::Result<(), std::fmt::Error> {