I'm a software engineer working as a full-stack developer using JavaScript, Node.js, and React. I write about my experiences in tech, tutorials, and share helpful hints.
/**
* Given a string containing checkbook transactions, format the transactions and calculate the running total
*/functionbalanceCheckbook(checkbook){letbalance=0lettotalExpense=0letbalancedCheckbook=''// Split the string into an array of transactions based on new lines.consttransactions=checkbook.split('\n')// Loop over the transactions to construct the checkbook and calculate total expense.transactions.forEach((transaction)=>{constsanitizedTransaction=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=sanitizedTransactionbalancedCheckbook+=`Original_Balance: ${sanitizedTransaction} \n`}else{consttransactionNumber=sanitizedTransaction[0]constdescription=sanitizedTransaction[1]constcost=sanitizedTransaction[2]constnewBalance=(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)}`returnbalancedCheckbook}/**
* Remove invalid characters from a transaction.
*/functionsanitizeInput(inputText){constremoveSpecialCharactersRegex=/[^A-Z0-9\s.]/gireturninputText.trim().replace(removeSpecialCharactersRegex,'')}
My JavaScript version:
Output: