JSFiddle - React, Tailwind, and code Playground
by joplomacedo
JavaScript
class Xyz {
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:
{
weekDay: {
creationDate1: quantityOfProductId,
creationDate2: quantityOfProductId
},
weekDay2: {
creationDate3: quantityOfProductId,
creationDate4: quantityOfProductId
},
...
}
the following code creates this obj. we'll call it dateAndQuantitiesByWeekDay:
*/
// create initial structure:
const dateAndQuantitiesByWeekDay = this.weekDays.reduce(( result, weekDay ) => {
return {
...result,
[weekDay]: {}
}
}, {});
//fill object with data
orders.forEach( order => {
const { creationDate, productLines } = order;
const productLineOfProductId = productLines.find( productLine => productLine.productId === productId );
if ( productLineOfProductId ) {
const creatonDateWeekDayIdx = creationDate.getDay();
const creationDateWeekDay = this.weekDays[creatonDateWeekDayIdx];
//check to see if an entry already exists
dateAndQuantitiesByWeekDay[creationDateWeekDay][creationDate] = dateAndQuantitiesByWeekDay[creationDateWeekDay][creationDate] || 0;
dateAndQuantitiesByWeekDay[creationDateWeekDay][creationDate] += productLineOfProductId.quantity;
}
...