Loan Payoff

by Vico Bertogli III

JavaScript

const person = {
  excess: 1000
};

const loans = [{
  description: "Loan 1",
  principle: 10000,
  interest: 0.05,
  term: 60
}, {
  description: "Loan 2",
  principle: 5000,
  interest: 0.045,
  term: 48
}, {
  description: "Loan 3",
  principle: 2000,
  interest: 0.085,
  term: 36
}, {
  description: "Loan 4",
  principle: 50000,
  interest: 0.045,
  term: 48
}];

var total = 0;

function totalPayment(arr) {
  if (!total) {
    arr.forEach(({
      ip
    }) => (total = total + ip));
  }

  return total;
}

function allocationFormula(loan, total) {
	var allocationPmt = Math.round(person.excess * (loan.ip / total));
  var allocation = ((allocationPmt/person.excess) * 100).toFixed(2);
  return Object.assign({}, loan, {
    allocation,
		allocationPmt
  });
}

function addInterestPayment(loan) {
  return Object.assign({}, loan, {
    ip: (loan.interest / 12) * loan.principle
  });
}

loans
  .map(loan => addInterestPayment(loan))
  .map((loan, index, arr) => allocationFormula(loan, totalPayment(arr)))
  .sort((a, b) => (b.allocation - a.allocation))
  .forEach(loan => {
    document.body.innerHTML += `<div>${JSON.stringify(loan)}</div>`;
  });