-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcalculator.js
58 lines (53 loc) · 1.79 KB
/
calculator.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
window.addEventListener('DOMContentLoaded', function () {
const form = document.getElementById("calc-form");
if (form) {
setupIntialValues();
form.addEventListener("submit", function (e) {
e.preventDefault();
update();
});
}
});
function getCurrentUIValues() {
return {
amount: +(document.getElementById("loan-amount").value),
years: +(document.getElementById("loan-years").value),
rate: +(document.getElementById("loan-rate").value),
}
}
// Get the inputs from the DOM.
// Put some default values in the inputs
// Call a function to calculate the current monthly payment
function setupIntialValues() {
const values = { amount: 10000, years: 10, rate: 4.5 };
const amountUI = document.getElementById("loan-amount");
amountUI.value = values.amount;
const yearsUI = document.getElementById("loan-years");
yearsUI.value = values.years;
const rateUI = document.getElementById("loan-rate");
rateUI.value = values.rate;
update();
}
// Get the current values from the UI
// Update the monthly payment
function update() {
const currentUIValues = getCurrentUIValues();
updateMonthly(calculateMonthlyPayment(currentUIValues));
}
// Given an object of values (a value has amount, years and rate ),
// calculate the monthly payment. The output should be a string
// that always has 2 decimal places.
function calculateMonthlyPayment(values) {
const monthlyRate = (values.rate / 100) / 12;
const n = Math.floor(values.years * 12);
return (
(monthlyRate * values.amount) /
(1 - Math.pow((1 + monthlyRate), -n))
).toFixed(2);
}
// Given a string representing the monthly payment value,
// update the UI to show the value.
function updateMonthly(monthly) {
const monthlyUI = document.getElementById("monthly-payment");
monthlyUI.innerText = "$" + monthly;
}