head-image.jpg

Recently, I had to travel through several countries by car 🚗. There were a lot of tolls to pay💰 and a lot of gasoline⛽ to fill. Which meant a lot of bills.

I collected the receipts🧾 along the way. And I planned to calculate, at the end of the trip, how much the whole journey cost me.

In the end I had a full bag of papers. Which meant that I had a lot of numbers to sum up.

I put them in a spreadsheet on my PC, ready to start calculating them by hand. And then, my programmer's mind started talking to me - why should I do all this manual work 🛠️ when I could write a short program to do it for me?

Don't get me wrong, I am aware there are a lot of other ways to do such calculations. But since I would like to call myself a programmer who loves to automate stuff, I wanted to do it myself. In the old school way.

I decided to use Node.js to solve this problem, mostly because I am quite comfortable with JavaScript. And this was supposed to be a very quick solution that I came up with during a cup of coffee ☕ in the morning.

So, here is what I did:

First, I filled in all the numbers I had in a txt file, each on a new line.

data-source-file.png

Then I wrote a small program that read the data source file, parsed the numbers on a new line as a separated value to be added, and did the summing up.

var fs = require('fs');

calculate = () => {
    fs.readFile('data.txt', 'utf8', (err, data) => {
        if (err) {
            throw new Error(err)
        }

        const arr = data.split('\\r\\n');
        const result = arr
            .filter(e => e)
            .map(parseFloat)
            .reduce((curr, next) => curr + next);
        console.log('RESULT: ', result);
    });
}

How I built this tool

I will say a few words about the implementation first. Then we'll go through a brief discussion about what other options I could have chosen.

This is a very short function that leverages a Node.js package, fs. It allows us to interact with the operating system (for example to read or write files to it). This is exactly what we need in order to be able to read our data source file.

The code itself follows the standard Node.js callback mechanism. And inside the callback function I used a bit of a functional approach: Piping multiple methods that get the data from the previous processing, do something on it, and then pass it to the next.

piping-methods.png

The first method, split, parses the data that is being read from the text file by using the \\r\\n separator. These symbols are used in the programming world to specify when a new line (in a file) is coming.

At this stage in our program, we have our numbers that have been read and parsed from the txt file. Now we use the filter method. This step strips the data out of any empty values.

Then we go for the map method - this is a JavaScript Array method that accepts a callback function. This callback will be executed on each of the arguments of a given array.