Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Sequence+RecursiveFlatten
extension Sequence {
func recursiveFlatten(_ childSelector: (Element) -> [Element]) -> [Element] {
var output: [Element] = []
for item in self {
output.append(item)
let newItems = childSelector(item)
if newItems.count > 0 {
output += newItems.recursiveFlatten(childSelector)
}
}
return output
}
func recursiveFlatMap<T>(_ transformer: (Element) -> (T, [Element])) -> [T] {
var output: [T] = []
for item in self {
let outItem = transformer(item)
output.append(outItem.0)
if outItem.1.count > 0 {
output += outItem.1.recursiveFlatMap(transformer)
}
}
return output
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment