Created
May 6, 2020 10:52
-
-
Save Dimillian/fd13afa625d49aaa53aff40edaf92225 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class ItemsViewModel: ObservableObject { | |
@Published var items: [Item] = [] | |
@Published var sortedItems: [Item] = [] | |
@Published var searchItems: [Item] = [] | |
@Published var searchText = "" | |
private var itemCancellable: AnyCancellable? | |
private var searchCancellable: AnyCancellable? | |
enum Sort: String, CaseIterable { | |
case name, buy, sell, from, set, similar | |
} | |
var category: Backend.Category { | |
didSet { | |
sort = nil | |
itemCancellable = Items.shared.$categories.sink { [weak self] items in | |
guard let self = self else { return } | |
self.items = items[self.category] ?? [] | |
} | |
} | |
} | |
var sort: Sort? { | |
didSet { | |
guard let sort = sort else { return } | |
switch sort { | |
case .name: | |
let compare: (String, String) -> Bool = sort == oldValue ? (<) : (>) | |
sortedItems = items.sorted{ compare($0.name, $1.name) } | |
case .buy: | |
let compare: (Int, Int) -> Bool = sort == oldValue ? (<) : (>) | |
sortedItems = items.filter{ $0.buy != nil}.sorted{ compare($0.buy!, $1.buy!) } | |
case .sell: | |
let compare: (Int, Int) -> Bool = sort == oldValue ? (<) : (>) | |
sortedItems = items.filter{ $0.sell != nil}.sorted{ compare($0.sell!, $1.sell!) } | |
case .from: | |
let compare: (String, String) -> Bool = sort == oldValue ? (<) : (>) | |
sortedItems = items.filter{ $0.obtainedFrom != nil}.sorted{ compare($0.obtainedFrom!, $1.obtainedFrom!) } | |
case .set: | |
let compare: (String, String) -> Bool = sort == oldValue ? (<) : (>) | |
sortedItems = items.filter{ $0.set != nil}.sorted{ compare($0.set!, $1.set!) } | |
case .similar: | |
let compare: (String, String) -> Bool = sort == oldValue ? (<) : (>) | |
sortedItems = items.filter{ $0.tag != nil}.sorted{ compare($0.tag!, $1.tag!) } | |
} | |
} | |
} | |
public init(category: Backend.Category) { | |
self.category = category | |
searchCancellable = $searchText | |
.debounce(for: .milliseconds(300), scheduler: DispatchQueue.main) | |
.removeDuplicates() | |
.filter { !$0.isEmpty } | |
.map(items(with:)) | |
.sink{ [weak self] in | |
self?.searchItems = $0 | |
} | |
itemCancellable = Items.shared.$categories | |
.sink { [weak self] in | |
self?.items = $0[category] ?? [] | |
} | |
} | |
private func items(with string: String) -> [Item] { | |
items.filter { | |
$0.name.lowercased().contains(string.lowercased()) | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment