satyacode
Background
Back to js-loops

08-emi-calculator.js

JavaScript
1/**
2 * 📱 Rohit ka Phone EMI Calculator
3 *
4 * Rohit ne naya phone liya hai EMI pe! Usse jaanna hai ki kitne months
5 * lagenge phone ka poora paisa chukane mein. Har month interest lagta hai
6 * remaining amount pe, aur phir EMI deduct hoti hai.
7 *
8 * Rules (use while loop):
9 *   - Start with principal amount (remaining balance)
10 *   - Each month:
11 *     1. Calculate interest = remaining * monthlyRate (monthlyRate is like 0.02 for 2%)
12 *     2. Add interest to remaining: remaining = remaining + interest
13 *     3. Deduct EMI: remaining = remaining - emi
14 *     4. Increment months count
15 *     5. Add emi to totalPaid
16 *   - Continue while remaining > 0
17 *   - In the last month, if remaining < emi, just pay what's left
18 *     (totalPaid += remaining before deduction, not full emi)
19 *
20 * Infinite loop protection:
21 *   - Agar EMI <= first month's interest (principal * monthlyRate),
22 *     toh loan kabhi khatam nahi hoga!
23 *     Return: { months: -1, totalPaid: -1, totalInterest: -1 }
24 *
25 * Validation:
26 *   - All three params must be positive numbers, else return
27 *     { months: -1, totalPaid: -1, totalInterest: -1 }
28 *
29 * @param {number} principal - Loan amount (phone ki price)
30 * @param {number} monthlyRate - Monthly interest rate (e.g., 0.02 for 2%)
31 * @param {number} emi - Monthly EMI amount
32 * @returns {{ months: number, totalPaid: number, totalInterest: number }}
33 *
34 * @example
35 *   calculateEMI(10000, 0.01, 2000)
36 *   // Month 1: 10000 + 100 = 10100, pay 2000, remaining = 8100
37 *   // Month 2: 8100 + 81 = 8181, pay 2000, remaining = 6181
38 *   // ... continues until remaining <= 0
39 *
40 *   calculateEMI(10000, 0.05, 400)
41 *   // First month interest = 500, EMI = 400 < 500, INFINITE LOOP!
42 *   // => { months: -1, totalPaid: -1, totalInterest: -1 }
43 */
44export function calculateEMI(principal, monthlyRate, emi) {
45  if(principal <= 0 || monthlyRate <= 0 || emi <= 0 || typeof principal !== "number"){
46    return { months: -1, totalPaid: -1, totalInterest: -1 }
47  }
48
49  let month = 0
50  let remaining = principal
51  let totalPaid = 0
52
53  let startInterest = remaining * monthlyRate
54  if(emi <= startInterest){
55    return { months: -1, totalPaid: -1, totalInterest: -1 }
56  }
57  while(remaining > 0){
58    let interest = remaining * monthlyRate
59    remaining = remaining + interest
60    if(remaining < emi){
61      totalPaid += remaining
62      remaining = 0
63    }else{
64      totalPaid += emi
65      remaining = remaining - emi
66    }
67    month ++
68  }
69  let totalInterest = Number((totalPaid - principal).toFixed(2))
70  return { months: month, totalPaid, totalInterest}
71}
72