-
Notifications
You must be signed in to change notification settings - Fork 0
/
compound.ts
65 lines (55 loc) · 942 Bytes
/
compound.ts
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
type T = {
/**
* The value to invest per month.
*/
value: number
/**
* The interest per year.
*/
interest: number
/**
* The number of years.
*/
years: number
/**
* Calculate the interest each month, or once per year.
*/
monthly: boolean
}
const compound = ({ value, interest, years, monthly }: T) => {
let total = 0
let invested = 0
Array(years * (monthly ? 12 : 1))
.fill(0)
.forEach(() => {
const v = value * (monthly ? 1 : 12)
total += v
total *= 1 + interest / (monthly ? 12 : 1)
invested += v
})
return {
/**
* The total investment plus interest.
*/
total,
/**
* The total investment.
*/
invested,
}
}
const monthly = compound({
value: 500,
interest: 0.073,
years: 30,
monthly: true,
})
console.log(monthly)
const yearly = compound({
value: 500,
interest: 0.073,
years: 30,
monthly: false,
})
console.log(yearly)
export default compound