feat: TaskProgress accumulation struct

This commit is contained in:
xeruf 2024-07-30 17:21:03 +03:00
parent 320575e9c3
commit 97450591e3
1 changed files with 48 additions and 11 deletions

View File

@ -86,18 +86,16 @@ impl Tasks {
} }
fn total_progress(&self, id: &EventId) -> Option<f32> { fn total_progress(&self, id: &EventId) -> Option<f32> {
self.get_by_id(id).and_then(|t| match t.pure_state() { self.tasks.get(id).map(|t| {
State::Closed => None, let state = t.pure_state();
State::Done => Some(1.0), let mut prog = TaskProgress::from(&state);
_ => { if state.is_open() {
let count = t.children.len() as f32; prog = prog + t.children
Some( .iter()
t.children .filter_map(|e| self.total_progress(e))
.iter() .sum()
.filter_map(|e| self.total_progress(e).map(|p| p / count))
.sum(),
)
} }
prog
}) })
} }
@ -486,6 +484,45 @@ impl<'a> Iterator for ParentIterator<'a> {
} }
} }
#[derive(Default, Copy, Clone)]
struct TaskProgress {
total: usize,
done: usize,
}
impl TaskProgress {
fn fraction(&self) -> f32 {
(self.done as f32) / (self.total as f32)
}
}
impl From<&State> for TaskProgress {
fn from(value: &State) -> Self {
TaskProgress {
total: (value != &State::Closed).into(),
done: (value == &State::Done).into(),
}
}
}
impl Display for TaskProgress {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
write!(f, "{}/{}", self.done, self.total,)
}
}
impl Add for TaskProgress {
type Output = TaskProgress;
fn add(self, rhs: Self) -> Self::Output {
TaskProgress {
done: self.done + rhs.done,
total: self.total + rhs.total,
}
}
}
impl Sum<TaskProgress> for TaskProgress {
fn sum<I: Iterator<Item = TaskProgress>>(iter: I) -> Self {
iter.fold(TaskProgress::default(), |acc, val| acc + val)
}
}
#[test] #[test]
fn test_depth() { fn test_depth() {
use std::sync::mpsc; use std::sync::mpsc;