From b2f9444ec9cab99299a5d63002b99663a0d8ba07 Mon Sep 17 00:00:00 2001 From: Kevin Wu Date: Thu, 25 Apr 2024 12:47:50 -0700 Subject: [PATCH] feat: refactor sort filters, aggregate default sort by start date --- lib/utils/filter.ts | 61 +++++++++++++++++++++++++++++---------------- 1 file changed, 39 insertions(+), 22 deletions(-) diff --git a/lib/utils/filter.ts b/lib/utils/filter.ts index 942e7be..302b75e 100644 --- a/lib/utils/filter.ts +++ b/lib/utils/filter.ts @@ -54,26 +54,43 @@ export function filterData( ); }); - const sortedResults = - filterValues.sort == "Alphabetical" - ? filteredResults.sort((courseA, courseB) => { - const nameA = courseA.courseCode + courseA.courseName; - const nameB = courseB.courseCode + courseB.courseName; - - return nameA.localeCompare(nameB); - }) - : filterValues.sort == "Tuition" - ? filteredResults.sort((courseA, courseB) => { - return courseA.tuition - courseB.tuition; - }) - : filterValues.sort == "Shortest Term" - ? filteredResults.sort((courseA, courseB) => { - const termLengthA = courseA.endDate - courseA.startDate; - const termLengthB = courseB.endDate - courseB.startDate; - - return termLengthA - termLengthB; - }) - : filteredResults; - - return sortedResults; + const sort = filterValues.sort; + + if (sort === "Alphabetical") { + filteredResults.sort((courseA, courseB) => { + const nameA = courseA.courseCode + courseA.courseName; + const nameB = courseB.courseCode + courseB.courseName; + + return nameA.localeCompare(nameB); + }); + } else if (sort === "Tuition") { + filteredResults.sort((courseA, courseB) => { + return courseA.tuition - courseB.tuition; + }); + } else if (sort === "Shortest Term") { + filteredResults.sort((courseA, courseB) => { + const termLengthA = courseA.endDate - courseA.startDate; + const termLengthB = courseB.endDate - courseB.startDate; + + return termLengthA - termLengthB; + }); + } else { + // Default Sort pushes past courses to the bottom of the list + + const pastCourses = filteredResults.filter( + (course) => new Date(course.startDate) <= new Date(), + ); + + const futureCourses = filteredResults.filter( + (course) => new Date(course.startDate) > new Date(), + ); + + const dateAggregatedCourses = []; + dateAggregatedCourses.push(...futureCourses); + dateAggregatedCourses.push(...pastCourses); + + return dateAggregatedCourses; + } + + return filteredResults; }