aboutsummaryrefslogtreecommitdiff
path: root/src/lib.rs
diff options
context:
space:
mode:
authorGuillermo Ramos2025-02-03 23:07:05 +0100
committerGuillermo Ramos2025-02-03 23:50:32 +0100
commit2a70a5e09e36d00b9b46ded6eda9fbaf0cc5352a (patch)
tree1537850b020abe836762dbf837c908f9569d5561 /src/lib.rs
parent097a8fba3c46ca83104763e897ee8dc035722071 (diff)
downloadhiccup-2a70a5e09e36d00b9b46ded6eda9fbaf0cc5352a.tar.gz
Refactor
Diffstat (limited to 'src/lib.rs')
-rw-r--r--src/lib.rs59
1 files changed, 34 insertions, 25 deletions
diff --git a/src/lib.rs b/src/lib.rs
index a0e1e61..fc75ebd 100644
--- a/src/lib.rs
+++ b/src/lib.rs
@@ -1,7 +1,7 @@
use std::fmt;
#[derive(Debug)]
-pub struct MortgageState {
+pub struct Mortgage {
period: u32,
capital: f64,
i12: f64,
@@ -9,7 +9,7 @@ pub struct MortgageState {
quotas: u32,
}
-impl fmt::Display for MortgageState {
+impl fmt::Display for Mortgage {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(
f,
@@ -23,46 +23,55 @@ impl fmt::Display for MortgageState {
}
}
-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 {
+impl Mortgage {
+ pub fn new(capital: f64, i1: f64, years: u32) -> Self {
let quotas = years * 12;
let i12 = i1 / 12.0;
- MortgageState {
+ Mortgage {
period: 0,
capital,
i12,
- quota: quota(capital, i12, quotas),
+ quota: Self::quota(capital, i12, quotas),
quotas,
}
}
- pub fn step(&mut self) {
+ pub fn run(&mut self) {
+ let to_pay = self.quota * self.quotas as f64;
+ let capital = self.capital;
+ let interest = to_pay - capital;
+
+ println!("Cuota | c\tIn\tAn\tCn");
+ while self.quotas > 0 {
+ println!("{self}");
+ self.step();
+ }
+ println!(
+ "\n== Total a pagar: {:.2} ({} cap + {interest:.2} int)",
+ to_pay, capital
+ );
+ println!(
+ "== Los intereses suponen un {:.2}% del capital",
+ 100. * interest / capital
+ );
+ println!("\n");
+ }
+
+ fn quota(capital: f64, i12: f64, quotas: u32) -> f64 {
+ capital * i12 / (1.0 - (1.0 + i12).powi(-(quotas as i32)))
+ }
+
+ 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 {
+ fn interests(&self) -> f64 {
self.i12 * self.capital
}
- pub fn amortized(&self) -> f64 {
+ 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();
- }
-}