feat: add sum method to Outcome
This commit is contained in:
@@ -2,3 +2,4 @@ pub mod die_new;
|
|||||||
pub mod die_roll;
|
pub mod die_roll;
|
||||||
pub mod handful_grab;
|
pub mod handful_grab;
|
||||||
pub mod handful_roll;
|
pub mod handful_roll;
|
||||||
|
pub mod outcome_sum;
|
||||||
|
|||||||
37
01.workspace/oxidice_lib/src/imp/outcome_sum.rs
Normal file
37
01.workspace/oxidice_lib/src/imp/outcome_sum.rs
Normal 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)));
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -3,7 +3,10 @@ use crate::*;
|
|||||||
// use std::str::FromStr;
|
// use std::str::FromStr;
|
||||||
|
|
||||||
#[derive(Debug, PartialEq, PartialOrd, Eq, Ord, Clone, Copy, Hash)]
|
#[derive(Debug, PartialEq, PartialOrd, Eq, Ord, Clone, Copy, Hash)]
|
||||||
pub enum E {}
|
pub enum E {
|
||||||
|
ProcessInput,
|
||||||
|
SumValues,
|
||||||
|
}
|
||||||
|
|
||||||
// impl Display for E {
|
// impl Display for E {
|
||||||
// fn fmt(&self, f: &mut std::fmt::Formatter) -> std::result::Result<(), std::fmt::Error> {
|
// fn fmt(&self, f: &mut std::fmt::Formatter) -> std::result::Result<(), std::fmt::Error> {
|
||||||
|
|||||||
Reference in New Issue
Block a user