Skip to content

Instantly share code, notes, and snippets.

@JadenGeller
Last active January 22, 2017 20:47
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save JadenGeller/e7bd0c949d82b3d3814995371713253d to your computer and use it in GitHub Desktop.
Save JadenGeller/e7bd0c949d82b3d3814995371713253d to your computer and use it in GitHub Desktop.
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