Skip to content

Instantly share code, notes, and snippets.

@muizidn
Last active June 23, 2021 08:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save muizidn/15153af8df862260e694516988e3ea9c to your computer and use it in GitHub Desktop.
Save muizidn/15153af8df862260e694516988e3ea9c to your computer and use it in GitHub Desktop.
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