The elves have prepared many gifts and wrapped many candies. But only good children will receive gifts. The others will get the coal. Santa Claus will decide. He records all the actions done by each child in an old notebook. This year, however, he asked for help to do it faster.
The puzzle: Making a list, checking it twice 📜
Problem # 6 in Dev Advent Calendar 🎅 is about arrays and how to filter them based on a calculated value. It is not a trivial problem. I think it’s a common situation. In a nutshell, it’s about reducing an array of values to a single number.
Sum of all elements of an array
Ok, maybe it is better to give an example. This is a child’s card:
Each child has a matched list of actions, some good, some not. Each action corresponds to a value. The sum of the values of each action is used to calculate a score:
In this case the score is positive, consequently the child deserves a prize:
All easy and simple as long as it is a single element. But what if we have hundreds, thousands, millions of children to bring gifts to? Well, Santa certainly can’t keep doing everything by hand. Fortunately, there is a method that is right for us, the Array.prototype.reduce()
reduce() iterates through all elements of an array and performs some operations for each element. The result of each operation is added to the previous result. This way I can calculate the sum of all effects.
Filter an array
The other part of the problem is a direct consequence of the first. After having found a way to establish whether a child deserves the gift or not, we can create two lists.
In the first we only put the children to bring the gifts to:
In the second instead we put the others:
In both cases I used the Array.prototype.filter() method to get only the required children from the list.
A single note to conclude. The very first thing to do is to import the list of children into the program. The list is in
json format so it requires special treatment. There are various ways to do this. One requires the use of the Node.js fs (filesystem) api:
However, it is a cumbersome way to do a simple thing.
The second method requires some experimental functions of Node.js. To activate them I had to modify the
package.json file by adding
Then in the
It works and is elegant.
In the future, you probably won’t need to use
Well, that’s all for today.