What would be the better way to process this data? Is this just a matter of personal preference? Guessing 2 is less prone to accidently modifying the monday...friday arrays and there is less code at this layer. Is there a best practices approach? Is there a performance difference?
// Arrays to hold what stock price belongs to what day of the week - Note these arrays are used some way down the line
var monday = [], tuesday = [], wednesday = [], thursday = [], friday = []
// Sort each stock date into a day of the week
FindDayFromDate(historyData, monday, tuesday, wednesday, thursday, friday);
// Find the average price for each day of the week
const avgPrices = FindAveragePricePerDay(monday, tuesday, wednesday, thursday, friday);
// Sort each stock date into a day of the week - sortedDays contains arrays of monday...friday
const sortedDays = FindDayFromDate(historyData);
// Find the average price for each day of the week - Expand sortedDays inside function to access monday...friday
const avgPrices = FindAveragePricePerDay(sortedDays);
A good function should always be free from side-effects. It should be pure and just do one specific job at a time. As a software programmer/developer, we must write source code that actually produce the output based on input. Such kind of strong pure function actually avoid all kind of side effects and code smell. Let's look at few examples to understand this.
Assume we have a function named as Greeting like below
function Greeting(name) {
return `Hello ${name}`;
}
It is pure because you will always get the output Hello {name} for the name passed via parameter. Let's have a look at another version of same function with many side-effects.
var greeting = "Hey";
function Greeting(name) {
return `${greeting} ${name}`;
}
Now, this function is not pure. Guess why ? Because we are not sure what output we will receive because function is actually dependent on the outer variable named as greeting . So if someone change the value of variable greeting to something else let's say Hello then obviously the output of function will change. So the function is now tightly coupled with the outer variable. That's why it is not pure function anymore.
So to conclude, you must have to write your function in such a way that there is no dependency and no side-effect and it will always do one job.
That is the best practice :)
Happy Coding :)
I believe the second Function "FindAveragePricePerDay" calling can be adjusted to act on single day, so that it can be reused on other places
const avgPrices = sortedDays.map(day => FindAveragePricePerDay(day));
/* you can also simplify the FindAveragePricePerDay using the reduce method
following this parameters array.reduce(function(total, currentValue, currentIndex, arr), initialValue)
so all the second line would be */
const avgPrices = day.reduce((t,c,i,arr) => t + c/arr.length, 0);
for more info about array.reduce check this