DEV Community

Discussion on: Daily Challenge #4 - Checkbook Balancing

Collapse
 
jaloplo profile image
Jaime López

Here my contribution in javascript:

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?;`;

// clean the input
let balanceInputs = input
  .split('\n')
  .map(x => x.split(' ')
  .filter(x => x.trim() !== ''));

// process input to create an object with all information
function processData(balance, ...inputs) {
  const data = {
    original : parseFloat(balance[0]),
    totalExpense: 0.0,
    averageExpense: 0.0
  };

  const orders = inputs.map(i => {
    const order = {
      id: parseInt(i[0]),
      concept: i[1].match(/[0-9a-zA-Z.\s]/g).reduce((acc, current) => acc.concat(current)),
      value: parseFloat(i[2]),
      balance: data.original - data.totalExpense - parseFloat(i[2])
    };
    data.totalExpense += order.value;
    return order;
  });

  data.averageExpense = data.totalExpense / orders.length;

  return {
    data: data,
    orders: orders
  }
}

// shows data in the console as a report
function createReport(report) {
  console.log('Original_Balance: ' + report.data.original.toFixed(fixed));
  report.orders.forEach(function(order) {
    console.log(order.id + ' ' + order.concept + ' ' + order.value.toFixed(fixed) + ' Balance ' + order.balance.toFixed(fixed));
  });
  console.log('Total expense ' + report.data.totalExpense.toFixed(fixed));
  console.log('Average expense ' + report.data.averageExpense.toFixed(fixed));
}


const fixed = 2; // set the number of decimal places
const data = processData(...balanceInputs); // process data
createReport(data); // shows the report