Skip to content

Commit

Permalink
Add sorting of years to mapper
Browse files Browse the repository at this point in the history
  • Loading branch information
dyedwiper committed Nov 28, 2023
1 parent 0bb2764 commit e2fa9a1
Showing 1 changed file with 17 additions and 13 deletions.
30 changes: 17 additions & 13 deletions apps/server/src/modules/school/api/mapper/years.response.mapper.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,17 +4,20 @@ import { MissingYearsLoggableException } from '../error/missing-years.loggable-e

export class YearsResponseMapper {
public static mapToResponse(school: School, schoolYears: SchoolYear[]): YearsResponse {
const schoolYearResponses = schoolYears.map((schoolYear) => schoolYear.getProps());
const sortedSchoolYears = schoolYears.sort(
(a, b) => a.getProps().startDate.getTime() - b.getProps().startDate.getTime()
);

const activeYear = this.computeActiveYear(school, schoolYears);
const nextYear = this.computeNextYear(schoolYears, activeYear);
const lastYear = this.computeLastYear(schoolYears, activeYear);
const schoolYearResponses = sortedSchoolYears.map((schoolYear) => schoolYear.getProps());
const activeYear = this.computeActiveYear(school, sortedSchoolYears);
const nextYear = this.computeNextYear(sortedSchoolYears, activeYear);
const lastYear = this.computeLastYear(sortedSchoolYears, activeYear);

const res = {
schoolYears: schoolYearResponses,
activeYear,
nextYear,
lastYear,
nextYear,
};

return res;
Expand All @@ -39,30 +42,31 @@ export class YearsResponseMapper {
return res;
}

private static computeNextYear(schoolYears: SchoolYear[], activeYear?: SchoolYearResponse): SchoolYearResponse {
private static computeLastYear(schoolYears: SchoolYear[], activeYear?: SchoolYearResponse): SchoolYearResponse {
const indexOfActiveYear = schoolYears.findIndex((schoolYear) => schoolYear.id === activeYear?.id);

const nextYear = schoolYears[indexOfActiveYear + 1];
const lastYear = schoolYears[indexOfActiveYear - 1];

if (!nextYear) {
if (!lastYear) {
throw new MissingYearsLoggableException();
}

const res = nextYear.getProps();
const res = lastYear.getProps();

return res;
}

private static computeLastYear(schoolYears: SchoolYear[], activeYear?: SchoolYearResponse): SchoolYearResponse {
private static computeNextYear(schoolYears: SchoolYear[], activeYear?: SchoolYearResponse): SchoolYearResponse {
const indexOfActiveYear = schoolYears.findIndex((schoolYear) => schoolYear.id === activeYear?.id);

const lastYear = schoolYears[indexOfActiveYear - 1];
const nextYear = schoolYears[indexOfActiveYear + 1];

if (!lastYear) {
if (!nextYear) {
console.log('nextYear', nextYear);
throw new MissingYearsLoggableException();
}

const res = lastYear.getProps();
const res = nextYear.getProps();

return res;
}
Expand Down

0 comments on commit e2fa9a1

Please sign in to comment.