Skip to content

Instantly share code, notes, and snippets.

@JadenGeller
Last active Jan 22, 2017
Embed
What would you like to do?
Cut a sequence given a predicate taking in successive elements
extension Collection where SubSequence: Sequence, SubSequence.Iterator.Element == Iterator.Element {
func cut(atSuccession shouldCut: (Iterator.Element, Iterator.Element) throws -> Bool) rethrows -> [Self.SubSequence] {
var (fromIndex, toIndex) = (startIndex, startIndex)
var result: [SubSequence] = []
for (x, y) in zip(self, dropFirst()) {
defer { toIndex = index(after: toIndex) }
guard try shouldCut(x, y) else { continue }
result.append(self[fromIndex...toIndex])
fromIndex = index(after: toIndex)
}
result.append(self[fromIndex...toIndex])
return result
}
}
// Example
// print([1, 2, 3, 4, 3, 2, 8, 9, 10, 9, 4, 3, 2].cut(atSuccession: { abs($0 - $1) > 1 }))
// -> [ArraySlice([1, 2, 3, 4, 3, 2]), ArraySlice([8, 9, 10, 9]), ArraySlice([4, 3, 2])]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment