DEV Community

loading...

Discussion on: Daily Challenge #4 - Checkbook Balancing

Collapse
petrdamborsky profile image
Petr Damborský

First time seeing these challenges. I don't know If there are any special requirements (e.g.: Should the code be production-ready? Will it be shared in a team? etc.) so I wrote just a simple solution for the task.

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

let output = 'Original_Balance: ';

const entries = input.split('\n').filter(e => e);
let balance = parseFloat(entries.splice(0, 1)[0].trim());
output += balance;

let spent = 0;
entries.forEach(e => {
  const data = e.split(' ').map(d => {
    if (isNaN(parseFloat(d))) {
      return d.replace(/[^\w\s.]/gi, '');
    } else {
      return parseFloat(d);
    }
  });
  const [check, category, amount] = [...data];
  spent += amount;
  output += `\n${check} ${category} ${amount} Balance ${(balance-spent).toFixed(2)}`;
});

output += `
Total expense ${spent.toFixed(2)}
Average expense ${(spent/entries.length).toFixed(2)}
`;

console.log(output);