DEV Community

Discussion on: Daily Challenge #4 - Checkbook Balancing

Collapse
 
ryansmith profile image
Ryan Smith

My JavaScript version:

/**
 * Given a string containing checkbook transactions, format the transactions and calculate the running total
 */
function balanceCheckbook (checkbook) {
  let balance = 0
  let totalExpense = 0
  let balancedCheckbook = ''

  // Split the string into an array of transactions based on new lines.
  const transactions = checkbook.split('\n')

  // Loop over the transactions to construct the checkbook and calculate total expense.
  transactions.forEach((transaction) => {
    const sanitizedTransaction = sanitizeInput(transaction).split(' ')

    // If this transaction only has one column, set it to be the starting balance. Otherwise, process a transaction.
    if (sanitizedTransaction.length === 1) {
      balance = sanitizedTransaction
      balancedCheckbook += `Original_Balance: ${sanitizedTransaction} \n`
    } else {
      const transactionNumber = sanitizedTransaction[0]
      const description = sanitizedTransaction[1]
      const cost = sanitizedTransaction[2]
      const newBalance = (balance -= cost).toFixed(2)

      totalExpense += parseFloat(cost)

      // Format the transaction into a string.
      balancedCheckbook += `${transactionNumber} ${description} ${cost} Balance ${newBalance} \n`
    }
  })

  balancedCheckbook += `Total expense ${totalExpense.toFixed(2)} \n`
  balancedCheckbook += `Average expense ${(totalExpense / (transactions.length - 1)).toFixed(2)}`

  return balancedCheckbook
}

/**
 * Remove invalid characters from a transaction.
 */
function sanitizeInput (inputText) {
  const removeSpecialCharactersRegex = /[^A-Z0-9\s.]/gi

  return inputText.trim().replace(removeSpecialCharactersRegex, '')
}
console.log(
  balanceCheckbook(
    `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?;`
  )
)

Output:

Original_Balance: 1233.00 
125 Hardware 24.8 Balance 1208.20 
123 Flowers 93.5 Balance 1114.70 
127 Meat 120.90 Balance 993.80 
120 Picture 34.00 Balance 959.80 
124 Gasoline 11.00 Balance 948.80 
123 Photos 71.4 Balance 877.40 
122 Picture 93.5 Balance 783.90 
132 Tires 19.00 Balance 764.90 
129 Stamps 13.6 Balance 751.30 
129 Fruits 17.6 Balance 733.70 
129 Market 128.00 Balance 605.70 
121 Gasoline 13.6 Balance 592.10 
Total expense 640.90 
Average expense 53.41