JSFiddle - React, Tailwind, and code Playground

by wisegorilla

JavaScript

(function(global) {
  // Sample Calculators:
  // http://www.pine-grove.com/Web%20Calculators/interest.htm

  var startingBalance = 200000.00,
    totalBalance = startingBalance,
    apr = (4.99 / 100),
    months = 240,
    interest,
    customMonthlyPayment = 1000,
    monthlyPayment,
    period;
    
  console.log('Starting Balance: $' + startingBalance.toFixed(2));
  console.log('APR: ' + apr);

  function getTotalBalance(balance, apr, months) {
    // Compute our total balance which is the starting balance + interest.
    // http://www.math.com/tables/general/interest.htm
    // http://en.wikipedia.org/wiki/Compound_interest#Compound
    return balance * Math.pow(1 + (apr / 360), 360 * (months / 12));          
  }

  function getMonthlyPayment(balance, apr, months) {
    // Get our monthly payment calculated by amortization (daily compounded).
    // http://www.vertex42.com/ExcelArticles/amortization-calculation.html
    // http://en.wikipedia.org/wiki/Amortization_calculator
    
    // We first need to figure out our monthly compounded payment rate.
    var r = Math.pow(1 + (apr / 360), (360 / 12)) - 1;
    
    // Now we can use our monthly rate to figure out our monthly payment.
    return balance * ((r * Math.pow(1 + r, months)) / (Math.pow(1 + r, months) - 1));          
  }

  function getPaymentPeriod(balance, apr, payment) {
    var i = 0, fixedPayment = payment.toFixed(2),
      totalBalance;
    
    // Determine how many payments will be needed for the specified balance,
    // APR and payment.  We want to stop our while loop once we've made more
    // than 360 monthly payments (30 years).
    while (balance > 0 && i < 360) {
      // The line below first calculates the amount of interest (daily compounded)
      // on the current balance.  Then we subtract the current balance from
      // the current balance with interest for the monthly payment.  That result
      // gives us the total amount of interest for the month.  We then subtract
    ...