DEV Community

loading...

Discussion on: Daily Challenge #4 - Checkbook Balancing

Collapse
mohamedelidrissi_98 profile image
Mohamed ELIDRISSI

My solution :)
Also available in my github repo: github.com/MohamedElidrissi/Daily-...

function balanceCheckbook(checkbook) {
  checkbook = checkbook.replace(/[^A-Za-z0-9\.\n ]/g, '');
  const reports = checkbook.match(/[0-9]+\s[A-Za-z]+\s[0-9]+(\.[0-9]{1,2})?/g);
  const expenses = checkbook.match(/ [0-9]+(\.[0-9]{1,2})?/g);
  const totalExpenses = expenses
    .reduce((p, c) => parseFloat(p) + parseFloat(c))
    .toFixed(2);
  let balance = checkbook.match(/^[0-9]+(\.[0-9]{1,2})?/g)[0];
  let output = `Original Balance: ${balance}\n`;

  reports.forEach((report, index) => {
    balance -= expenses[index];
    output += `${report} Balance ${balance.toFixed(2)}\n`;
  });

  output += `Total expense ${totalExpenses}\n`;
  output += `Average expense ${(totalExpenses / expenses.length).toFixed(2)}`;

  return output;
}