Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Performs filter on a sectioned array
struct SectionedArrayFiltering<T> {
struct Result {
let filteredSection: [Int]
let filteredItemsBySection: [Int:[T]]
}
let input: [[T]]
func filter(
sectionFilter: (Int) -> Bool = {_ in true},
itemFilter: (T) -> Bool
) -> Result {
var includedSections = [Int]()
var includedItemsBySection = [Int:[T]]()
var section = 0
for items in input {
if !sectionFilter(section) {
section += 1
continue
}
for item in items {
if itemFilter(item) {
var arr = includedItemsBySection[section] ?? []
arr.reserveCapacity(items.count)
arr.append(item)
includedItemsBySection[section] = arr
}
}
if includedItemsBySection[section] != nil {
includedSections.append(section)
}
section += 1
}
#if SectionedArrayFiltering_DEBUG
print("SectionedArrayFiltering:", "Included Sections", includedSections)
print("SectionedArrayFiltering:", "Included Items By Section", includedItemsBySection)
#endif
return Result(
filteredSection: includedSections,
filteredItemsBySection: includedItemsBySection
)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment