aboutsummaryrefslogtreecommitdiff
path: root/src/lib.rs
blob: a0e1e61715521b80449c3d0e317856e3d2208549 (plain) (blame)
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
use std::fmt;

#[derive(Debug)]
pub struct MortgageState {
    period: u32,
    capital: f64,
    i12: f64,
    quota: f64,
    quotas: u32,
}

impl fmt::Display for MortgageState {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(
            f,
            "{:5} | {:4.2}\t{:.2}\t{:.2}\t{:.2}",
            self.period,
            self.quota,
            self.interests(),
            self.amortized(),
            self.capital
        )
    }
}

pub fn quota(capital: f64, i12: f64, quotas: u32) -> f64 {
    capital * i12 / (1.0 - (1.0 + i12).powi(-(quotas as i32)))
}

impl MortgageState {
    fn new(capital: f64, i1: f64, years: u32) -> Self {
        let quotas = years * 12;
        let i12 = i1 / 12.0;
        MortgageState {
            period: 0,
            capital,
            i12,
            quota: quota(capital, i12, quotas),
            quotas,
        }
    }

    pub fn step(&mut self) {
        self.period += 1;
        self.quotas -= 1;
        self.capital = (1.0 + self.i12) * self.capital - self.quota;
    }

    pub fn interests(&self) -> f64 {
        self.i12 * self.capital
    }

    pub fn amortized(&self) -> f64 {
        self.quota - self.interests()
    }
}

pub fn run_mortgage(capital: f64, i12: f64, years: u32) {
    let mut state = MortgageState::new(capital, i12, years);

    println!("Total a pagar: {}\n\n", state.quota * state.quotas as f64);

    println!("Cuota | c\tIn\tAn\tCn");
    while state.quotas > 0 {
        println!("{state}");
        state.step();
    }
}