DEV Community

loading...

Discussion on: Daily Challenge #4 - Checkbook Balancing

Collapse
caleb_rudder profile image
Caleb Rudder

A little late to the party, but trying to work on a few skills. I thought I'd attempt to work on using closures a bit on this one:

const myCheckbook = checkbook(testData);
myCheckbook.balanceCheckbook();

function checkbook(input){
    let userData = removeClutter(input);
    let totalBalance = 0;
    let totalExpenses = 0;
    let expenseCounter = 0;
    let averageExpense = 0;
    function removeClutter(data){
        let cleanData = data.replace(/([^a-zA-Z0-9\s\.])/g, '');
        return cleanData.split('\n');
    }

    function addExpense(expense){
        totalExpenses += expense;
        totalBalance -= expense;
        expenseCounter++;
        averageExpense = totalExpenses / expenseCounter;
    };

    const balanceCheckbook = function(){
        for(let i = 0; i<userData.length; i++){
            if(i == 0){
                totalBalance = userData[0];
                console.log('Original_Balance: ' + totalBalance);
            }else{
                let line = userData[i].split(" ");
                addExpense(parseFloat(line[2]));
                console.log(userData[i] + " Balance: " + totalBalance.toFixed(2));
            }
        }
        console.log("Total Expenses: " + totalExpenses.toFixed(2));
        console.log("Average expense: " + averageExpense.toFixed(2));
    };

    return{
        userData: userData,
        balanceCheckbook: balanceCheckbook
    }
}