From 3a322d96666b8da2b615ffd1c245f3a2f3d0cd90 Mon Sep 17 00:00:00 2001 From: "(quasar) nebula" Date: Thu, 27 Apr 2023 16:16:53 -0300 Subject: data: refactor sortByDate to handle latestFirst directly Fixes #180. This enables sortByDate to keep dateless items at the end even when sorting with latest first, and conveniently reduces the ops since there's no need for .reverse() before and after the sort anymore. It also cleans logic by deduplicating latest-first code in compositional sort functions using sortByDate. --- src/util/wiki-data.js | 30 +++++------------------------- 1 file changed, 5 insertions(+), 25 deletions(-) (limited to 'src/util') diff --git a/src/util/wiki-data.js b/src/util/wiki-data.js index 5a0e241a..7a3f4144 100644 --- a/src/util/wiki-data.js +++ b/src/util/wiki-data.js @@ -181,6 +181,7 @@ export function sortByName(data, { } export function sortByDate(data, { + latestFirst = false, getDate = (o) => o.date, } = {}) { return data.sort((a, b) => { @@ -191,7 +192,7 @@ export function sortByDate(data, { // together in the same array. If that's the case, we put all items // without dates at the end. if (ad && bd) { - return ad - bd; + return (latestFirst ? bd - ad : ad - bd); } else if (ad) { return -1; } else if (bd) { @@ -292,18 +293,8 @@ export function sortChronologically(data, { getName, getDate, } = {}) { - if (latestFirst) { - // Double reverse: Since we reverse after sorting by date, also reverse - // after sorting A-Z, so the second reverse restores A-Z relative - // positioning (for entries with the same date). - sortAlphabetically(data, {getDirectory, getName}); - data.reverse(); - sortByDate(data, {getDate}); - data.reverse(); - } else { - sortAlphabetically(data, {getDirectory, getName}); - sortByDate(data, {getDate}); - } + sortAlphabetically(data, {getDirectory, getName}); + sortByDate(data, {latestFirst, getDate}); return data; } @@ -334,18 +325,7 @@ export function sortAlbumsTracksChronologically(data, { // released on the same date, they'll still be grouped together by album, // and tracks within an album will retain their relative positioning (i.e. // stay in the same order as part of the album's track listing). - - if (latestFirst) { - // Like in sortChronologically, double reverse: Since we reverse after - // sorting by date, also reverse before, so that items with the same date - // are flipped relative to each other twice - that maintains the original - // relative ordering! - data.reverse(); - sortByDate(data, {getDate}); - data.reverse(); - } else { - sortByDate(data, {getDate}); - } + sortByDate(data, {latestFirst, getDate}); return data; } -- cgit 1.3.0-6-gf8a5