DEV Community

dev.to staff
dev.to staff

Posted on

Daily Challenge #4 - Checkbook Balancing

Good morning, everyone.

Don’t say I didn’t warn you, we’re moving from letters to numbers with this challenge.

Today’s challenge comes from user @g964 on CodeWars.

You are given a small checkbook to balance that is given to you as a string. Sometimes, this checkbook will be cluttered by non-alphanumeric characters.

The first line shows the original balance. Each other (not blank) line gives information: check number, category, and check amount.

You need to clean the lines first, keeping only letters, digits, dots, and spaces. Next, return the report as a string. On each line of the report, you have to add the new balance. In the last two lines, return the total expenses and average expense. Round your results to two decimal places.

Example Checkbook

1000.00
125 Market 125.45
126 Hardware 34.95
127 Video 7.45
128 Book 14.32
129 Gasoline 16.10

Example Solution

Original_Balance: 1000.00
125 Market 125.45 Balance 874.55
126 Hardware 34.95 Balance 839.60
127 Video 7.45 Balance 832.15
128 Book 14.32 Balance 817.83
129 Gasoline 16.10 Balance 801.73
Total expense 198.27
Average expense 39.65

Challenge 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?;

Good luck and happy coding!


Thank you to CodeWars, who has licensed redistribution of this challenge under the 2-Clause BSD License!

Want to propose a challenge for a future post? Email yo+challenge@dev.to with your suggestions!

Top comments (39)

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)}
`)
Collapse
 
dak425 profile image
Donald Feury • Edited

Here is my attempt, did it in Go: Github

This executable boils down to:

package main

import (
    "fmt"

    "github.com/Dak425/dev-to-challenge-4-go/pkg/checkbook/memory"
)

func main() {
    raw := `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?;`

    cb := memory.NewInMemoryCheckBook(raw)

    fmt.Print(cb.FullReport())
}

Output:

Starting Balance: 1233.00
[1] -> Check Number: 125, Category: Hardware, Amount: 24.80, Remaining Balance: 1208.20
[2] -> Check Number: 123, Category: Flowers, Amount: 93.50, Remaining Balance: 1114.70
[3] -> Check Number: 127, Category: Meat, Amount: 120.90, Remaining Balance: 993.80
[4] -> Check Number: 120, Category: Picture, Amount: 34.00, Remaining Balance: 959.80
[5] -> Check Number: 124, Category: Gasoline, Amount: 11.00, Remaining Balance: 948.80
[6] -> Check Number: 123, Category: Photos, Amount: 71.40, Remaining Balance: 877.40
[7] -> Check Number: 122, Category: Picture, Amount: 93.50, Remaining Balance: 783.90
[8] -> Check Number: 132, Category: Tires, Amount: 19.00, Remaining Balance: 764.90
[9] -> Check Number: 129, Category: Stamps, Amount: 13.60, Remaining Balance: 751.30
[10] -> Check Number: 129, Category: Fruits, Amount: 17.60, Remaining Balance: 733.70
[11] -> Check Number: 129, Category: Market, Amount: 128.00, Remaining Balance: 605.70
[12] -> Check Number: 121, Category: Gasoline, Amount: 13.60, Remaining Balance: 592.10
Total Costs: 640.90
Average Cost: 53.41

Also, wooo first post on here 🎉

Collapse
 
kerrishotts profile image
Kerri Shotts

Here's my take (JavaScript). A few notes:

  • I sort by line #, and then by category
  • The first line might actually be blank, so I trim the input
  • Categories are assumed to be single words (no spaces allowed)
  • Output includes digit grouping by current locale
  • Full code (incl some basic tests): gist.github.com/kerrishotts/461a90...

const sanitize = str => str.replace(/[^0-9A-Za-z\.\s]/g, "");

const notBlank = str => str !== "";

const extract = str => {
    const [ line, category, expense ] = str.split(/\s+/);
    return { line: Number(line), category, expense: Number(expense) };
};

const byLineAndCategory = (a, b) => a.line < b.line 
    ? -1 : a.line > b.line 
        ? 1 : a.category < b.category 
            ? -1 : a.category > b.category 
                ? 1 : 0;

const balanceReducer = (
    {openingBalance, totalExpenses, entries}, 
    {line, category, expense}
) => {
    const newTotal = totalExpenses + expense;
    const newBalance = openingBalance - newTotal;
    return {
        openingBalance,
        totalExpenses: newTotal,
        averageExpense: newTotal / (entries.length + 1),
        entries: [ ...entries, {line, category, expense, balance: newBalance }]
    }
};

const round2 = n => (Math.round(n * 100) / 100)
    .toLocaleString(undefined, {
        style: "decimal",
        minimumFractionDigits: 2,
        useGrouping: true
    });

const balanceCheckbook = (checkbook) => {
    const [openingBalanceStr, ...entries] = 
        sanitize(checkbook)
        .trim()
        .split("\n")
        .filter(notBlank);

    const openingBalance = Number(openingBalanceStr);

    const initialState = { 
            openingBalance, 
            entries: [], 
            averageExpense: 0, 
            totalExpenses: 0
    };

    const report = 
        entries
        .map(extract)
        .sort(byLineAndCategory)
        .reduce( balanceReducer, initialState );

    return `
Original Balance: ${round2(report.openingBalance)}
${report.entries.map(({line, category, expense, balance}) =>
`${line} ${category} ${round2(expense)} Balance ${round2(balance)}`
).join("\n")}
Total Expenses: ${round2(report.totalExpenses)}
Average Expense: ${round2(report.averageExpense)}
`.trim();
};

Enter fullscreen mode Exit fullscreen mode
Collapse
 
zerquix18 profile image
I'm Luis! \^-^/

I think is the most scalable solution since you first move all the data to a manipulable format, deal with it and then output it.

Collapse
 
johncip profile image
jmc • Edited

I'm impressed by how short many of the solutions are.

Clojure:

(ns checkbook
  (:require [clojure.string :refer [join split]]))

;; split line into tokenized "entry"
(defn tokens [line]
  (map read-string (re-seq #"(?:\w|\.)+" line)))

;; append running balance onto entries
(defn with-running-balance [[start & entries]]
  (reduce
    (fn [acc entry]
      (let [prev-bal  (last (last acc))
            cur-bal   (- prev-bal (last entry))
            new-entry (conj (vec entry) "Balance" cur-bal)]
        (conj acc new-entry)))
    [["Original_Balance" (last start)]]
    entries))

;; output entry as string, with numbers rounded
(defn format-entry [xs]
  (case (count xs)
    2 (apply format "%s %.2f" xs)
    5 (apply format "%s %s %.2f %s %.2f" xs)))

;; append running balance, include total & average, format nums
(defn balance [s]
  (let [lines   (split s #"\n")
        entries (map tokens lines)
        $$      (map last (rest entries))]
    (join "\n"
      (map format-entry
        (conj (with-running-balance entries)
              ["Total expense" (apply + $$)]
              ["Average expense" (/ (apply + $$) (count $$))])))))
Collapse
 
martyhimmel profile image
Martin Himmel • Edited

PHP

It wasn't specified, but I sorted the check order. Also noticed that checks 123 and 129 are repeated two and three times, respectively, while 126, 128, and 131 are missing. I'm guessing the duplicate number were supposed to be the missing numbers. 😄

$text = '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?;';

function checkbook_report(string $str) {
    $data = format_checkbook_string($str);
    $balance = floatval(array_shift($data));
    $output = 'Original Balance: ' . number_format($balance, 2) . PHP_EOL;
    $expenses = [];

    sort($data);

    foreach ($data as $index => $line) {
        $parts = explode(' ', $line);
        // handles multi-word categories (even though they don't exist in this challenge)
        foreach ($parts as $line_segment) {
            if ($line_segment != end($parts)) {
                $output .= "$line_segment ";
            }
        }
        $expenses[] = floatval(end($parts));
        $balance -= end($expenses);
        $output .= number_format(end($parts), 2) . ', Balance: ' . number_format($balance, 2) . PHP_EOL;
    }

    $total_expenses = array_sum($expenses);
    $output .= 'Total expenses: ' . number_format($total_expenses, 2) . PHP_EOL;
    $output .= 'Average expense: ' . number_format($total_expenses / count($expenses), 2) . PHP_EOL;
    return $output;
}

function format_checkbook_string(string $str) {
    $data = explode(PHP_EOL, $str);
    return array_map('filter_line', $data);
}

function filter_line(string $line) {
    return preg_replace('/[^\w\s.]+/', '', $line);
}

echo checkbook_report($text);
Collapse
 
v613 profile image
Ceban Dumitru • Edited

BASH

#!/bin/bash
input='challenge.txt';
declare -a checkbook;
total=0;
for line in $(cat ${input}|tr -cd [' ','0-9','.','A-Z','a-z','\n']);do
    checkbook+=("${line}");
done;

echo "Original_Balance: "${checkbook[0]};
for (( i = 1; i < ${#checkbook[@]}; i+=3 )); do
    echo ${checkbook[@]:${i}:3};
    total=`echo "scale=2;${total} + ${checkbook[${i}+2]}" |bc`;
done;
average=`echo "scale=2;${total}/((${#checkbook[@]}-1)/3)"|bc`;

echo "Total expense: " ${total};
echo "Average expense: " ${average};

result

Collapse
 
alvaromontoro profile image
Alvaro Montoro • Edited

JavaScript

This is going to be one of those "don't do this at home" types of code (or maybe "do it at home but not at work"). I tried to do it as a single chain of commands, assuming that the string is going to be valid. It can be further cleaned and reduced, I'll try later.

Here is the code commented step-by-step:

const generateReport = checkbook => {
  let current = 0;
                   // use regular expressions to remove unwanted characters
  return checkbook.replace(/[^0-9a-z\. \n]/gi, "")
                   // separate the string into an array splitting by new line
                  .split("\n")
                   // update each value to include the total at the end
                  .map((val, index) => {
                    current = index === 0 ? val : (current - val.split(" ")[2]).toFixed(2);
                    return index === 0 ? "Original Balance: " + val : val + ` ${current}`;
                  })
                   // convert array into string again
                  .join("\n")
                   // concatenate the total and average
                  .concat(`\nTotal expense: ${(checkbook.split("\n")[0] - current).toFixed(2)}`)
                  .concat(`\nAverage expense: ${((checkbook.split("\n")[0] - current)/(checkbook.split("\n").length-1) || 0).toFixed(2)}`);
}

You can see it working on this CodePen.

Collapse
 
alvaromontoro profile image
Alvaro Montoro

And as an extra, here is a version in which the checks are also sorted:

const generateReport = checkbook => {
  let current = 0;
  return checkbook.replace(/[^0-9a-z\. \n]/gi, "")
                  .split("\n")
                  .sort((a,b) => {
                    const arrA = a.split(" ");
                    const arrB = b.split(" ");
                    if (arrA.length > arrB.length) {
                      return 1;
                    } else if (arrB.length > arrA.length) {
                      return -1;
                    } else {
                      return parseInt(arrA[0]) > parseInt(arrB[0]) ? 1 : -1;
                    }
                  })
                  .map((val, index) => {
                    current = index === 0 ? val : (current - val.split(" ")[2]).toFixed(2);
                    return index === 0 ? "Original Balance: " + val : val + ` ${current}`;
                  })
                  .join("\n")
                  .concat(`\nTotal expense: ${(checkbook.split("\n")[0] - current).toFixed(2)}`)
                  .concat(`\nAverage expense: ${((checkbook.split("\n")[0] - current)/(checkbook.split("\n").length-1) || 0).toFixed(2)}`);
}
Collapse
 
jaloplo profile image
Jaime López

Here my contribution in javascript:

const input = `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?;`;

// clean the input
let balanceInputs = input
  .split('\n')
  .map(x => x.split(' ')
  .filter(x => x.trim() !== ''));

// process input to create an object with all information
function processData(balance, ...inputs) {
  const data = {
    original : parseFloat(balance[0]),
    totalExpense: 0.0,
    averageExpense: 0.0
  };

  const orders = inputs.map(i => {
    const order = {
      id: parseInt(i[0]),
      concept: i[1].match(/[0-9a-zA-Z.\s]/g).reduce((acc, current) => acc.concat(current)),
      value: parseFloat(i[2]),
      balance: data.original - data.totalExpense - parseFloat(i[2])
    };
    data.totalExpense += order.value;
    return order;
  });

  data.averageExpense = data.totalExpense / orders.length;

  return {
    data: data,
    orders: orders
  }
}

// shows data in the console as a report
function createReport(report) {
  console.log('Original_Balance: ' + report.data.original.toFixed(fixed));
  report.orders.forEach(function(order) {
    console.log(order.id + ' ' + order.concept + ' ' + order.value.toFixed(fixed) + ' Balance ' + order.balance.toFixed(fixed));
  });
  console.log('Total expense ' + report.data.totalExpense.toFixed(fixed));
  console.log('Average expense ' + report.data.averageExpense.toFixed(fixed));
}


const fixed = 2; // set the number of decimal places
const data = processData(...balanceInputs); // process data
createReport(data); // shows the report
Collapse
 
neotamizhan profile image
Siddharth Venkatesan

Ruby

class Checkbook

  def initialize
    @entries = []
    @balance = 0.0
    @orig_bal = 0.0
    load!
  end

  def total_expense
    @entries.map {|e| e.check_amount}.sum
  end

  def average_expense
    total_expense / @entries.size
  end

  def load!
    content = File.readlines("input.txt")    
    @balance = @orig_bal = content[0].to_f    
    (1..content.size-1).each do |n|
      line = content[n]
      @entries << CheckEntry.new(line)
    end    
    calculate_balance!
  end

  def calculate_balance!
    @entries.sort!  
    @entries.each do |entry|
      #puts "#{@balance} : #{entry.check_amount}"
      @balance -= entry.check_amount
      entry.running_balance = @balance
    end
  end

  def to_s      
    disp = []
    disp << "%.2f" % @orig_bal
    disp << @entries.map {|e| e.to_s}
    disp << "Total Expenses = #{"%.2f" % total_expense}"
    disp << "Average Expenses = #{"%.2f" % average_expense}"

    disp.join("\n")
  end
end

class CheckEntry

  attr_accessor :check_number, :category, :check_amount, :running_balance


  def initialize(line)
    @check_number = 0
    @category = ""
    @check_amount = 0.0
    @running_balance = 0.0    
    load!(line)
  end 

  def load!(line)    
    line = sanitize(line)      
    matches = /^(\d+)\s+(.*?)\s(.*)$/.match(line)
    @check_number = matches[1].to_i
    @category = matches[2]
    @check_amount = matches[3].to_f    
  end

  def sanitize(line)
    line.gsub(/([^\d\w\s\.])/, '')
  end

  def to_s
    "#{@check_number} #{@category} #{"%.2f" % @check_amount} #{"%.2f" % @running_balance}"
  end

   def <=>(other)
    @check_number <=> other.check_number
  end
end

puts Checkbook.new

Output :

1233.00
120 Picture 34.00 1199.00
121 Gasoline 13.60 1185.40
122 Picture 93.50 1091.90
123 Flowers 93.50 998.40
123 Photos 71.40 927.00
124 Gasoline 11.00 916.00
125 Hardware 24.80 891.20
127 Meat 120.90 770.30
129 Stamps 13.60 756.70
129 Fruits 17.60 739.10
129 Market 128.00 611.10
132 Tires 19.00 592.10
Total Expenses = 640.90
Average Expenses = 53.41
Collapse
 
cvanpoelje profile image
cvanpoelje
tidyCheckbook = checkbook => {
  sum = 0;
  rules = checkbook.split("\n");
  rules[0] = `Original_balance: ${rules[0]}`;
  amountOfRules = rules.length-1;
  return rules
    .map(rule => {
      rule = rule.replace(/[;?!{},]/g, "").split(" ");
      return rule =  { id: rule[0], category: rule[1], checkAmount: parseFloat(rule[2]).toFixed(2)}
    })
    .sort((a, b) => a.id - b.id)
    .map(rule => {
      return (`${rule.id} ${rule.category} ${isNaN(rule.checkAmount) ? '':rule.checkAmount}`)})
    .join("\n")
    .concat(`\n======================\nTotal expense: ${sum}\nAverage expense: ${sum / amountOfRules}`
    )
}
Collapse
 
kesprit profile image
kesprit

My solution in Swift :

/// Daily Challenge #4 - Checkbook Balancing

let 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?;
"""

func analyseCheckbook(checkbook: String) {
    typealias CheckbookEntry = (number: String, description: String, expense: Double)
    let roundFormat = "%.2f"
    var count: Double = 0
    var totalExpense: Double = 0
    var checkbookEntries = [CheckbookEntry]()

    var cleanCheckbook = checkbook.filter { char -> Bool in
        char.isLetter || char.isNumber || char.isWhitespace || char == "."
    }.components(separatedBy: .newlines)

    let originalBalance = Double(cleanCheckbook.removeFirst()) ?? 0
    cleanCheckbook.forEach { checkbook in
        let line = checkbook.components(separatedBy: .whitespaces)
        if line.count == 3 {
            checkbookEntries.append(CheckbookEntry(number: line[0], description: line[1], expense: Double(line[2]) ?? 0))
        }
    }

    print("Original_Balance: \(originalBalance)")

    checkbookEntries.forEach { entry in
        count += entry.expense
        totalExpense += entry.expense
        print("\(entry.number) \(entry.description) Balance \(String(format: roundFormat, originalBalance - count))")
    }
    let averageExpense = (totalExpense / Double(checkbookEntries.count))
    print("Total expense \(String(format: roundFormat, totalExpense))")
    print("Average expense \(String(format: roundFormat, averageExpense))")
}
Collapse
 
costica profile image
costica

i think it is quite funny how most of the answers here ignore basically half of the requirement and do not print the new balance :)

i think it should be a signal you are ignoring the task and creating something that seems fun for you to solve ( looking at how everyone handles the 'checks numbers' in his own way, even tho it was not a req :) )

just my 2 cents, but always open for a good constructive namecalling kind of talk hihi

Collapse
 
barbaraips profile image
Bárbara Perdigão

Java:

class Main {

    public static void main(String[] args) {

        Scanner scan = new Scanner(System.in);
        String input = scan.nextLine();
        String report = balanceCheckbook(input);

        System.out.println(report);
    }

    static String  balanceCheckbook(String input){

        DecimalFormat df = new DecimalFormat("####.00");

        ArrayList<String> checkbook = new ArrayList<>(Arrays.asList(input.replaceAll("(\\b\\D\\W)", " ").split("\\n")));

        float currentBalance = parseFloat(checkbook.get(0));
        float totalExpense = 0;

        StringBuilder reportBuilder = new StringBuilder(("Original_Balance: " + df.format(currentBalance) + "\n"));

        for (int count = 1; count <checkbook.size(); count++){
            String[] values = checkbook.get(count).replaceAll("\\b(\\s{2})", " ").split("\\s");
            totalExpense += parseFloat(values[2]);
            currentBalance -= parseFloat(values[2]);
            checkbook.set(count, values[0] + " " + values[1] + " " + df.format(parseFloat(values[2])));
            reportBuilder.append(checkbook.get(count)).append(" Balance ").append(df.format(currentBalance)).append("\n");
        }

        float averageExpense = totalExpense / (checkbook.size() - 1);

        reportBuilder.append("Total expense ").append(df.format(totalExpense)).append("\n")
            .append("Average expense ").append(df.format(averageExpense));

        return reportBuilder.toString().replace(",", ".");
    }
}
Collapse
 
cloudyhug profile image
cloudyhug

Haskell

import Data.Char

processCheckbook :: String -> String
processCheckbook checkbook =
  unlines $ prettyBalance : (reverse prettyEntries) ++ [prettyTotal, prettyAverage]
  where
    (originalBalance : entries) = lines $ filter (\x -> or [isAlphaNum x, isSpace x, x == '.']) checkbook
    processEntry (prettyEntries, total, balance) entry =
      let expense = read $ words entry !! 2
          newBalance = balance - expense
      in ((entry ++ " Balance " ++ show newBalance) : prettyEntries, total + expense, newBalance) 
    (prettyEntries, totalExpense, _) = foldl processEntry ([], 0, read originalBalance) entries
    prettyBalance = "Original_Balance: " ++ originalBalance
    prettyTotal = "Total expense " ++ show totalExpense
    prettyAverage = "Average expense " ++ show (totalExpense / (fromIntegral $ length entries))
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');
}