Re-wrote sorting code to be smaller and easier to understand

This commit is contained in:
Phil Viso 2019-09-13 08:03:56 -05:00
parent 269364a337
commit 61d3dae10e
1 changed files with 9 additions and 17 deletions

View File

@ -32,28 +32,21 @@ struct ArticleSorter {
private static func sortedByFeedName<T: SortableArticle>(articles: [T],
sortByDateDirection: ComparisonResult) -> [T] {
// Group articles by feed - feed ID is used to differentiate between
// Group articles by "feed-feedID" - feed ID is used to differentiate between
// two feeds that have the same name
var groupedArticles = Dictionary(grouping: articles) { "\($0.sortableName.lowercased())-\($0.sortableFeedID)" }
let groupedArticles = Dictionary(grouping: articles) { "\($0.sortableName.lowercased())-\($0.sortableFeedID)" }
return groupedArticles
.sorted { $0.key < $1.key }
.flatMap { (tuple) -> [T] in
let (_, articles) = tuple
// Sort the articles within each group
for tuple in groupedArticles {
groupedArticles[tuple.key] = sortedByDate(articles: tuple.value,
sortDirection: sortByDateDirection)
return sortedByDate(articles: articles, sortDirection: sortByDateDirection)
}
// Flatten the articles dictionary back into an array sorted by feed name
var sortedArticles: [T] = []
for feedName in groupedArticles.keys.sorted() {
sortedArticles.append(contentsOf: groupedArticles[feedName] ?? [])
}
return sortedArticles
}
private static func sortedByDate<T: SortableArticle>(articles: [T],
sortDirection: ComparisonResult) -> [T] {
let articles = articles.sorted { (article1, article2) -> Bool in
return articles.sorted { (article1, article2) -> Bool in
if article1.sortableDate == article2.sortableDate {
return article1.sortableArticleID < article2.sortableArticleID
}
@ -63,7 +56,6 @@ struct ArticleSorter {
return article1.sortableDate < article2.sortableDate
}
return articles
}
}