Intro
A short blog on how you can simplify your code by using a functional approach.
Moreover, I will try to help a team manager by using a functional approach (e.g. filter, map and reduce)
Players and functions
A team manager want to extract some insights from a list of players, like the age of the players or the players that playing in a specific position or some statistics.
Let's see how we can help him with some functional constructs.
The players list is the following (I am a little bit biased):
list all the ages - map
The team manager needs a list with the players ages. As data manipulators we can isolate the ages!
First approach: Extracing the ages by using for constructs
In all the above cases we had to initialize an array, using map there is no need, plus the code looks more readable.
Second approach: Using map
In both approaches the result is the same (the list of all ages):
Team needs a left back! filter
Team manager said that there is an urgent need for a left back, again as data magicians we can do that easily!
First approach: using for
Second approach: Using filter
In both approaches the result is the same, but in the second approach the code is claener and there is no need for array initialization:
(Go for tsimikas! :) )
Useful stat - reduce
The team manager wants to know the sum of players ages (don't ask why...). Let's help him! This time we are going to give him only the functional approach, reduce!
How the reduce works:
the first argument is a callback function that performs the desired calculation between all the array elements, the intermediate caclulations are stored in acc (also the final result at the end)
the second argument is the initial value of the acc
you can understand reduce better through an example:
In our case the reduce is going to perform the following:
in the first iteration, the value of the acc is 0 (the initial value)
the next variable contains the age of "roberto carlos" the age of the first player in the list, then an addition is performed 0 + 35 = 35, this is the new
acc valuein the next iteration the acc has the value of 35 and next 24 (the age of the second player), so the acc will be updated with the valye 59
the process is repeated till the end of the list, at the end will have the sum of all ages
Cheers!
Top comments (1)
Using functions like filter, map, and reduce for player data makes it so much easier to manage Tiro al Palo and extract insights. It’s a clean way to keep the code readable and efficient.