Skip to content

Instantly share code, notes, and snippets.

@JadenGeller
Created September 13, 2020 03:18
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 JadenGeller/6d241569d3ad78e3840e4baef33f028d to your computer and use it in GitHub Desktop.
Save JadenGeller/6d241569d3ad78e3840e4baef33f028d to your computer and use it in GitHub Desktop.
Segment
extension Array {
func segment(atJunction shouldSegment: (Element, Element) throws -> Bool) rethrows -> [ArraySlice<Element>] {
var result: [ArraySlice<Element>] = []
var previousValue: Element?
for (index, value) in enumerated() {
defer { previousValue = value }
if let previousValue = previousValue, try shouldSegment(previousValue, value) {
result.append(self[(result.last?.endIndex ?? startIndex)..<index])
}
}
return result
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment