aboutsummaryrefslogtreecommitdiff
path: root/src/habit.rs
blob: 967e425fd77bec9cf3845db1275421152c0bdc8a (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
use std::collections::HashMap;

use chrono::NaiveDate;

#[derive(Debug)]
pub struct Habit<T> {
    name: String,
    stats: HashMap<NaiveDate, T>,
    goal: T,
}

impl<T> Habit<T>
where
    T: Copy,
{
    pub fn new(name: &str, goal: T) -> Habit<T> {
        return Habit {
            name: name.to_owned(),
            stats: HashMap::new(),
            goal,
        };
    }

    pub fn get_name(&self) -> String {
        return self.name.to_owned();
    }

    pub fn get_by_date(&self, date: NaiveDate) -> Option<&T> {
        self.stats.get(&date)
    }

    pub fn insert_entry(&mut self, date: NaiveDate, val: T) {
        *self.stats.entry(date).or_insert(val) = val;
    }
}

impl Habit<bool> {
    pub fn toggle(&mut self, date: NaiveDate) {
        if let Some(v) = self.stats.get_mut(&date) {
            *v ^= true
        } else {
            self.insert_entry(date, true);
        }
    }
    pub fn reached_goal(&self, date: NaiveDate) -> bool {
        *self.get_by_date(date).unwrap_or(&false)
    }
}

impl Habit<u32> {
    pub fn increment(&mut self, date: NaiveDate) {
        if let Some(v) = self.stats.get_mut(&date) {
            *v += 1;
        } else {
            self.insert_entry(date, 1);
        }
    }
    pub fn decrement(&mut self, date: NaiveDate) {
        if let Some(v) = self.stats.get_mut(&date) {
            if *v > 0 {
                *v -= 1;
            } else {
                *v = 0;
            };
        }
    }
    pub fn set(&mut self, date: NaiveDate, val: u32) {
        *self.stats.entry(date).or_insert(val) = val;
    }
    pub fn reached_goal(&self, date: NaiveDate) -> bool {
        if let Some(v) = self.get_by_date(date) {
            if *v >= self.goal {
                return true;
            }
        }
        return false;
    }
}