DEV Community

loading...

Discussion on: Daily Challenge #4 - Checkbook Balancing

Collapse
jasman7799 profile image
Jarod Smith
function balanceCheckbook(checkbook = '') {
  if(typeof(checkbook) !== 'string')
    throw new Error('input must be a string');

  checkbook = checkbook.trim();

  let originalBalance = 0;
  let entries = checkbook.split('\n');
  let balance = originalBalance;

  // exclude the orginalBalance at the top
  let totalEntries = entries.length - 1;

  for(index in entries) {
    let entry = entries[index];

    // clean the line
    entry = entry.replace(/[^\.\w\d ]+/g, '');

    // parse the line
    if(index == 0)
    {
      originalBalance = parseFloat(entry);
      balance = originalBalance;
      console.log(`Original_Balance: ${originalBalance.toFixed(2)}`);
    }
    else
    {
      let section = entry.split(' ');
      let expenseString = section[2]; 
      let expense = parseFloat(expenseString);

      balance -= expense;
      console.log(`${entry} Balance ${balance.toFixed(2)}`);
    } 
  }

  // compute summaries
  let totalExpense = originalBalance - balance;
  let averageExpense = totalExpense/totalEntries; 

  // print summary
  console.log(`Total expense ${totalExpense.toFixed(2)}`);
  console.log(`Average expense ${averageExpense.toFixed(2)}`)
}
const input = `
1233.00
125 Hardware;! 24.8?;
123 Flowers 93.5
127 Meat 120.90
120 Picture 34.00
124 Gasoline 11.00
123 Photos;! 71.4?;
122 Picture 93.5
132 Tires;! 19.00,?;
129 Stamps 13.6
129 Fruits{} 17.6
129 Market;! 128.00?;
121 Gasoline;! 13.6?;
`;
balanceCheckbook(input);