2019-09-08 23:48:50 +02:00
|
|
|
//
|
|
|
|
// ArticleSorter.swift
|
|
|
|
// NetNewsWire
|
|
|
|
//
|
|
|
|
// Created by Phil Viso on 9/8/19.
|
|
|
|
// Copyright © 2019 Ranchero Software. All rights reserved.
|
|
|
|
//
|
|
|
|
|
|
|
|
import Articles
|
|
|
|
import Foundation
|
|
|
|
|
|
|
|
protocol SortableArticle {
|
|
|
|
var sortableName: String { get }
|
|
|
|
var sortableDate: Date { get }
|
2019-09-13 14:43:28 +02:00
|
|
|
var sortableArticleID: String { get }
|
2019-11-15 03:11:41 +01:00
|
|
|
var sortableWebFeedID: String { get }
|
2019-09-08 23:48:50 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
struct ArticleSorter {
|
2019-09-13 14:43:28 +02:00
|
|
|
|
2019-09-08 23:48:50 +02:00
|
|
|
static func sortedByDate<T: SortableArticle>(articles: [T],
|
|
|
|
sortDirection: ComparisonResult,
|
|
|
|
groupByFeed: Bool) -> [T] {
|
2019-09-13 14:43:28 +02:00
|
|
|
if groupByFeed {
|
|
|
|
return sortedByFeedName(articles: articles, sortByDateDirection: sortDirection)
|
|
|
|
} else {
|
|
|
|
return sortedByDate(articles: articles, sortDirection: sortDirection)
|
2019-09-08 23:48:50 +02:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// MARK: -
|
2019-09-13 14:43:28 +02:00
|
|
|
|
|
|
|
private static func sortedByFeedName<T: SortableArticle>(articles: [T],
|
|
|
|
sortByDateDirection: ComparisonResult) -> [T] {
|
2019-09-13 15:03:56 +02:00
|
|
|
// Group articles by "feed-feedID" - feed ID is used to differentiate between
|
2019-09-13 14:43:28 +02:00
|
|
|
// two feeds that have the same name
|
2019-11-15 03:11:41 +01:00
|
|
|
let groupedArticles = Dictionary(grouping: articles) { "\($0.sortableName.lowercased())-\($0.sortableWebFeedID)" }
|
2019-09-13 15:03:56 +02:00
|
|
|
return groupedArticles
|
|
|
|
.sorted { $0.key < $1.key }
|
|
|
|
.flatMap { (tuple) -> [T] in
|
|
|
|
let (_, articles) = tuple
|
|
|
|
|
|
|
|
return sortedByDate(articles: articles, sortDirection: sortByDateDirection)
|
2019-09-08 23:48:50 +02:00
|
|
|
}
|
2019-09-13 14:43:28 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
private static func sortedByDate<T: SortableArticle>(articles: [T],
|
|
|
|
sortDirection: ComparisonResult) -> [T] {
|
2019-09-13 15:03:56 +02:00
|
|
|
return articles.sorted { (article1, article2) -> Bool in
|
2019-09-13 14:43:28 +02:00
|
|
|
if article1.sortableDate == article2.sortableDate {
|
|
|
|
return article1.sortableArticleID < article2.sortableArticleID
|
|
|
|
}
|
|
|
|
if sortDirection == .orderedDescending {
|
|
|
|
return article1.sortableDate > article2.sortableDate
|
|
|
|
}
|
|
|
|
|
|
|
|
return article1.sortableDate < article2.sortableDate
|
|
|
|
}
|
2019-09-08 23:48:50 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
}
|