From bff3c287304c38eca3ec2c9c8b814681d4d7cead Mon Sep 17 00:00:00 2001 From: schroda <50052685+schroda@users.noreply.github.com> Date: Sun, 30 Jun 2024 13:40:10 +0200 Subject: [PATCH] Extract chapter sort into function --- src/components/chapter/util.tsx | 34 +++++++++++++++++++++++++-------- 1 file changed, 26 insertions(+), 8 deletions(-) diff --git a/src/components/chapter/util.tsx b/src/components/chapter/util.tsx index 8d52747a..01b52b11 100644 --- a/src/components/chapter/util.tsx +++ b/src/components/chapter/util.tsx @@ -79,6 +79,30 @@ function bookmarkedFilter(bookmarked: NullAndUndefined, { isBookmarked: } } +const sortChapters = ( + chapters: TChapter[], + { sortBy, reverse }: Pick, +): TChapter[] => { + const sortedChapters: TChapter[] = [...chapters]; + + switch (sortBy) { + case 'source': + sortedChapters.sort((a, b) => a.sourceOrder - b.sourceOrder); + break; + case 'fetchedAt': + sortedChapters.sort((a, b) => Number(a.fetchedAt ?? 0) - Number(b.fetchedAt ?? 0)); + break; + default: + // nothing to do + } + + if (reverse) { + sortedChapters.reverse(); + } + + return sortedChapters; +}; + export function filterAndSortChapters(chapters: TChapter[], options: ChapterListOptions): TChapter[] { const filtered = options.active ? chapters.filter( @@ -88,14 +112,8 @@ export function filterAndSortChapters(chapters: TChapter[], options: ChapterList bookmarkedFilter(options.bookmarked, chp), ) : [...chapters]; - const sorted = - options.sortBy === 'fetchedAt' - ? filtered.toSorted((a, b) => Number(a.fetchedAt ?? 0) - Number(b.fetchedAt ?? 0)) - : filtered.toSorted((a, b) => a.sourceOrder - b.sourceOrder); - if (options.reverse) { - sorted.reverse(); - } - return sorted; + + return sortChapters(filtered, options); } export const useChapterOptions = (mangaId: number) =>