I have this method that attaches the year and year's rowspan for a TD and Quarter and a Quarter's rowspan for the TD.
Year and Quarter are 2 columns in an Angular Material Table which are calculated from an array of objects one of which property of the object is a date string.
Here is a demo for the code: https://stackblitz.com/edit/angular-ynpmdk
This is my method which works fine, I wanted to review if I can shorten this method, looks very ugly. Open to suggestions.
/**
* Gets the year/quarter span information and filters what data is to be shown in tabs
* @param data launch data all
* @param mode which tab we are on
*/
getGroupData(data: DATA[]) {
data.sort((a:DATA, b:DATA) =>
!a.date ? -1
: !b.date
? -1 : (new Date(a.date).getTime() - new Date(b.date).getTime())
);
let cYear = data[0];
let cQuarter = data[0];
for (let i = 0; i < data.length; i++) {
if (data[i].date) {
const curDate = new Date(data[i].date);
const dateYear = new Date(cYear.date);
const dateQuarter = new Date(cQuarter.date);
// Get Year span and Year values
data[i].year = curDate.getFullYear();
cYear.year = dateYear.getFullYear();
if (cYear.year === data[i].year) {
cYear.yearSpan = (cYear.yearSpan || 0) + 1;
} else {
cYear = data[i];
cYear.yearSpan = 1;
}
// Get Quarter span and Quarter values
data[i].quarter = this.getQuarter(curDate.getMonth());
cQuarter.quarter = this.getQuarter(dateQuarter.getMonth());
if (cQuarter.quarter === data[i].quarter) {
cQuarter.quarterSpan = (cQuarter.quarterSpan || 0) + 1;
} else {
cQuarter = data[i];
cQuarter.quarterSpan = 1;
}
} else {
cYear = cQuarter = data[i];
cYear.yearSpan = cYear.quarterSpan = 1;
cYear.year = cYear.quarter = 'TBD';
if (i === data.length - 1) {
break;
} else {
cYear = cQuarter = data[i + 1];
}
}
}
return data;
}
/**
* Get the quarter info from month index
* @param month month index
*/
private getQuarter(month: number): string {
return `Q${Math.ceil((month + 1) / 3)}`;
}
A sample data object looks like
{position: 1, name: 'Hydrogen', date: '2016-01-11', symbol: 'H'}
when the method is invoked the record becomes
{
position: 1,
name: 'Hydrogen',
date: '2016-01-11',
symbol: 'H',
year: 2016,
quarter: 'Q1',
yearSpan: 5, // The other records have 5 entries pertaining to this year
quarterSpan: 2, // The other records have 2 entries pertaining to this quarter of this year
}
Here is a demo for the code: https://stackblitz.com/edit/angular-ynpmdk?file=src%2Fapp%2Ftable-basic-example.ts