DEV Community

loading...

Discussion on: Daily Challenge #4 - Checkbook Balancing

Collapse
gnsp profile image
Ganesh Prasad
const round2 = n => Math.round(n*100)/100;
const balance = book => {
    const lines = book.replace(/[^\da-z\.\s]/gi, '').split('\n');
    const [originalBalance, ...expenses] = lines.map(line => line.match(/\d+\.\d{1,2}/)[0]).map(Number);
    const balances = expenses.reduce((acc, expense, index) => [ ...acc, acc[index] - expense ], [originalBalance]).slice(1);
    const totalExpense = expenses.reduce((x, y) => x + y, 0);
    return [
        `Original_Balance: ${originalBalance}`,
        ...lines.slice(1).map((line, index) => `${line} Balance ${round2(balances[index])}`),
        `Total expense ${round2(totalExpense)}`,
        `Average expense ${round2(totalExpense / expenses.length)}`
    ].join('\n');
}