Skip to content

Instantly share code, notes, and snippets.

@special-character
Last active January 4, 2019 22:53
Show Gist options
  • Save special-character/9e760aa342088ffa834a037deb573c1c to your computer and use it in GitHub Desktop.
Save special-character/9e760aa342088ffa834a037deb573c1c to your computer and use it in GitHub Desktop.
/*
* A calculator for determining how much interest will be paid on a loan and an estimate on how long the loan will be for.
* Inputs: Principle, interest rate of the loan, and monthly payment
*/
const PRINCIPAL = 4000
const INTEREST_RATE = .0525
const MONTHLY_PAYMENT = 300
const calculateInterest = (principal, interestRate, monthlyPayment) => {
let principalLeft = principal
let totalInterest = 0
let totalPayment = 0
let numMonths = 0
while (principalLeft >= 0) {
const monthInterest = (principalLeft * interestRate) * (1/12)
const appliedToPrincipal = monthlyPayment - monthInterest
const nextPrincipal = principalLeft - appliedToPrincipal
totalPayment += nextPrincipal < 0 ? principalLeft + monthInterest : monthlyPayment
totalInterest += monthInterest
principalLeft = nextPrincipal
numMonths++
/*
console.log(principalLeft+': month '+ numMonths+ ' interest ' + monthInterest + ' totalInterest ' + totalInterest + ' applied principal '+ appliedToPrincipal +' principal left ' + principalLeft + ' ')
*/
}
console.log('Total Paid: ' + totalPayment)
console.log('Interest: ' + totalInterest)
console.log('Months: ' + numMonths)
}
console.log('PRINCIPAL ' + PRINCIPAL + ' Interest rate ' + INTEREST_RATE + ' Total Payment ' + MONTHLY_PAYMENT)
calculateInterest(PRINCIPAL, INTEREST_RATE, MONTHLY_PAYMENT)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment