Created
October 24, 2019 10:10
-
-
Save bugrym/b6d368254e430e6251df1c8743480a9d 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
private func buildTree(allProducts:[Product], handler: @escaping(()->Void)) { | |
let group = DispatchGroup() | |
let asyncQueue = DispatchQueue(label: "com.shop.tree.build.queue", qos: .utility, attributes: .concurrent, autoreleaseFrequency: .inherit, target: nil) | |
var byCategory:[ProductSection] = [] | |
group.enter() | |
asyncQueue.async { | |
for product in allProducts { | |
// If we have same section already | |
if let sectionIndex = byCategory.firstIndex(where: { (section) -> Bool in | |
section.category == product.category | |
}) { | |
// If we have same subsection already | |
if let subSectionIndex = byCategory[sectionIndex].subSections.firstIndex(where: { (subSection) -> Bool in | |
subSection.subCategory == product.category | |
}) { | |
byCategory[sectionIndex].subSections[subSectionIndex].products.append(product) | |
} else { | |
guard let subCategory = product.subCategory else { return } | |
let newSubSection = ProductSubSection(subCategory: subCategory, products: [product]) | |
byCategory[sectionIndex].subSections.append(newSubSection) | |
} | |
} else { | |
// If we have to create a new one section | |
guard let category = product.category, let subCategory = product.subCategory else { return } | |
let newSection = ProductSection(category: category) | |
let newSubSection = ProductSubSection(subCategory: subCategory, products: [product]) | |
newSection.subSections.append(newSubSection) | |
byCategory.append(newSection) | |
} | |
} | |
} | |
group.notify(queue: .main) { | |
handler() | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment