JSFiddle - React, Tailwind, and code Playground
by joplomacedo
JavaScript
/*
The getProductAvgByWeekDay function is expecting an object with the following structure.
[
{
creationDate: Date,
orderLines: [
{
quantity: Number,
productId: String,
...
},
...
],
...
},
...
]
*/
class ProductDataCalculations {
constructor() {
this.weekDays = ['SUNDAY', 'MONDAY', 'TUESDAY', 'WEDNESDAY', 'THURSDAY', 'FRIDAY', 'SATURDAY'];
}
getProductAvgByWeekDay( orders, productId ) {
//create initial structure of object to be returned
const result = this.weekDays.reduce(( result, weekDay ) => {
return {
...result,
[weekDay]: 0
}
}, {});
/* for calculation purposes, we want a structure like the following:
{
"weekDay1": {
day1: quantityOfProductId, //quantity of orders that happened on day X.
day2: quantityOfProductId
},
weekDay2: {
day4: quantityOfProductId,
day3: quantityOfProductId
},
...
}
the following code creates this obj. we'll call it dayQuantitiesByWeekDay:
*/
// create initial structure:
const dayQuantitiesByWeekDay = this.weekDays.reduce(( result, weekDay ) => {
return {
...result,
[weekDay]: {}
}
}, {});
//fill object with data
orders.forEach( order => {
const { creationDate, productLines } = order;
const productLineOfProductId = productLines.find( productLine => {
return productLine.productId === productId;
});
if ( productLineOfProductId ) {
const creationDateWeekDayIdx = creationDate.getDay();
const creationDateWeekDay =...