Last active
June 23, 2021 08:32
-
-
Save muizidn/15153af8df862260e694516988e3ea9c to your computer and use it in GitHub Desktop.
Performs filter on a sectioned array
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
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