-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
69 lines (62 loc) · 1.98 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
export default function calculateHomeLoan(loanValue, years, rate, frequency) {
// Check for negative values
if(loanValue < 0 || years < 0 || rate < 0 || frequency < 0) {
return {
monthlyPayment: NaN,
totalPayment: NaN,
totalInterest: NaN
};
}
// Check for null values
if(loanValue === 0 && years === 0 && rate === 0 && frequency === 0) {
return {
monthlyPayment: 0,
totalPayment: 0,
totalInterest: 0
};
}
// Check for undefined values
if(rate === 0) {
return {
monthlyPayment: Math.round(loanValue / years / frequency * 100) / 100,
totalPayment: loanValue,
totalInterest: 0
};
}
// Check for 0 values
if(years === 0) {
return {
monthlyPayment: loanValue,
totalPayment: loanValue,
totalInterest: 0
};
}
// Check for 0 values
if(frequency === 0) {
return {
monthlyPayment: loanValue,
totalPayment: loanValue,
totalInterest: 0
};
}
// Calculate the monthly rate
let monthlyRate = rate / frequency / 100;
// Calculate the number of payments
let numberOfPayments = years * frequency;
// Calculate the monthly payment
let monthlyPayment = loanValue * monthlyRate / (1 - Math.pow(1 + monthlyRate, -numberOfPayments));
// Calculate the total payment and total interest
let totalPayment = monthlyPayment * numberOfPayments;
// Calculate the total interest
let totalInterest = totalPayment - loanValue;
// Round to the nearest cent
monthlyPayment = Math.round(monthlyPayment * 100) / 100;
totalPayment = Math.round(totalPayment * 100) / 100;
totalInterest = Math.round(totalInterest * 100) / 100;
// Return the results
return {
monthlyPayment: monthlyPayment,
totalPayment: totalPayment,
totalInterest: totalInterest
};
}