DEV Community

loading...

Discussion on: Daily Challenge #4 - Checkbook Balancing

Collapse
zerquix18 profile image
I'm Luis! \^-^/

Here's my attempt:

const checkbook = `
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?;
`.trim()

const round = value => Math.round(value * 100) / 100

const cleanedCheckBook = checkbook.replace(/[^A-Za-z0-9\s\.]/gmi, '')
const lines = cleanedCheckBook.split("\n")
const originalBalance = parseFloat(lines.shift())

let totalExpenses = 0
const expenses = []

const linesProcessed = lines.map(line => {
  const [number, category, expense] = line.split(' ')
  const expenseFloat = parseFloat(expense)
  totalExpenses += expenseFloat
  expenses.push(expenseFloat)

  const currentBalance = originalBalance - totalExpenses

  return `${number} ${category} ${round(expense)} Balance ${round(currentBalance)}`
}).join("\n")

const averageSpent = expenses.reduce((total, sum) => total + sum) / expenses.length

console.log(`
Original_Balance: ${round(originalBalance)}
${linesProcessed}
Total Expenses: ${round(totalExpenses)}
Average spent: ${round(averageSpent)}
`)

My attempt with comments:

const checkbook = `
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?;
`.trim() // this will remove spaces, tabs, and breaklines \n at the beginning and end

// Math.round doesn't round to X number of digits so I'm using this hacky method
const round = value => Math.round(value * 100) / 100
// skip all non A-Za-z0-9\s\. caracters, globally, multiline, and case insensitive
const cleanedCheckBook = checkbook.replace(/[^A-Za-z0-9\s\.]/gmi, '')
// make an array where every element is a line
const lines = cleanedCheckBook.split("\n")
// extract the first element and save the value in float
const originalBalance = parseFloat(lines.shift())

let totalExpenses = 0
const expenses = [] // for the average

// go thru each line and change it
const linesProcessed = lines.map(line => {
  const [number, category, expense] = line.split(' ')
  const expenseFloat = parseFloat(expense)

  totalExpenses += expenseFloat
  expenses.push(expenseFloat)

  const currentBalance = originalBalance - totalExpenses

  return `${number} ${category} ${round(expense)} Balance ${round(currentBalance)}`
}).join("\n")

const averageSpent = expenses.reduce((total, sum) => total + sum) / expenses.length

console.log(`
Original_Balance: ${round(originalBalance)}
${linesProcessed}
Total Expenses: ${round(totalExpenses)}
Average spent: ${round(averageSpent)}
`)