DEV Community

Discussion on: Daily Challenge #4 - Checkbook Balancing

Collapse
dimitrilahaye profile image
Dimitri Lahaye

JS below :)

function balanced(note) {
  clean = (s) => s.match(/([a-z0-9\s.])/gi).join('');
  let balance, total = 0, average = 0;
  return [...note.split('\n').map((n, i) => {
    const a = clean(n);
    if (!i) {
      balance = parseFloat(a).toFixed(2);
      return `Original_Balance: ${balance}`;
    }
    let [num, obj, amount] = a.split(' ');
    total += parseFloat(amount);
    average = total / (i);
    balance -= amount;
    return `${num} ${obj} ${amount} Balance ${balance.toFixed(2)}`;
  }),
  `Total expense ${total.toFixed(2)}`,
  `Average expense ${average.toFixed(2)}`]
  .join('\n');
}