-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
95 lines (80 loc) · 2.77 KB
/
index.js
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
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
let btn = document.querySelector('#submit')
let form = document.querySelector('form.mortgage-group')
btn.addEventListener('click', event => {
event.preventDefault()
mortgageMath()
})
form.addEventListener('submit', event => {
event.preventDefault()
mortgageMath()
})
const mortgageMath = () => {
let pmt = calculatePayment()
let target = document.querySelector('#mortgage-payment')
target.innerHTML = formatter.format(pmt)
toggleTable()
}
const calculatePayment = () => {
let principal = document.getElementById('principal').value
if (typeof principal === "string") {
principal = principal.replace(',','')
}
let rate = document.getElementById('rate').value / 12 / 100
let term = document.getElementById('term').value
let a = Math.pow((1 + rate), term) //interest money cost factor
let numerator = a * rate //the top part of the equation
let denominator = a - 1 //the bottom part of the equation
let payment = principal * numerator / denominator
totalPaid(payment, term, principal)
amortize(payment, rate, term, principal)
return payment
}
const formatter = new Intl.NumberFormat('en-US', {
style: 'currency',
currency: 'USD',
minimumFractionDigits: 2
})
const amortize = (payment, rate, term, balance) => {
let amortizationSchedule = []
for(let i = 0; i < term + 1; i++) {
let interestPaydown = balance * rate
let principalPaydown = payment - interestPaydown
balance -= principalPaydown
if(balance > payment) {
amortizationSchedule.push([i, principalPaydown, interestPaydown, balance])
}
if(balance < 0) {
break
}
}
createTable(amortizationSchedule)
}
const createTable = (array) => {
for(let i = 1; i < array.length - 1; i++) {
let table = document.getElementById('table-to-fill')
let row = table.insertRow()
array[i].forEach((el, index) => {
let cell = row.insertCell()
if (index == 0) {
cell.innerHTML = el
} else {
cell.innerHTML = formatter.format(el)
}
})
}
}
const toggleTable = () => {
let mortgageSchedule = document.querySelector('.table-body-schedule')
mortgageSchedule.style.visibility = 'visible'
}
const totalPaid = (payment, term, principal) => {
let totalPayment = document.querySelector('#mortgage-total')
let total = payment * term
totalPayment.innerHTML = `${formatter.format(total)}`
calculateInterest(total, principal)
}
const calculateInterest = (total, principal) => {
let totalInterest = document.querySelector('#interest-total')
let interest = total - principal
totalInterest.innerHTML = `${formatter.format(interest)}`
}