-
-
Notifications
You must be signed in to change notification settings - Fork 2.6k
Expand file tree
/
Copy pathpayback.rs
More file actions
30 lines (26 loc) · 728 Bytes
/
payback.rs
File metadata and controls
30 lines (26 loc) · 728 Bytes
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
/// Returns the payback period in years
/// If investment is not paid back, returns None.
pub fn payback(cash_flow: &[f64]) -> Option<usize> {
let mut total = 0.00;
for (year, &cf) in cash_flow.iter().enumerate() {
total += cf;
if total >= 0.00 {
return Some(year);
}
}
None
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_payback() {
let cash_flows = vec![-1000.0, 300.0, 400.0, 500.0];
assert_eq!(payback(&cash_flows), Some(3)); // paid back in year 3
}
#[test]
fn test_no_payback() {
let cash_flows = vec![-1000.0, 100.0, 100.0, 100.0];
assert_eq!(payback(&cash_flows), None); // never paid back
}
}