Skip to content

Instantly share code, notes, and snippets.

@JadenGeller
Last active November 1, 2023 05:02
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/104b26d21a82afd7a3683769fa2bd712 to your computer and use it in GitHub Desktop.
Save JadenGeller/104b26d21a82afd7a3683769fa2bd712 to your computer and use it in GitHub Desktop.
grouping function like split or chunked, but gives you access to the whole group so far in the predicate
extension Collection {
func grouping(isMember: (SubSequence, Element) throws -> Bool) rethrows -> [SubSequence] {
var result: [SubSequence] = []
var start = self.startIndex
for end in self.indices.dropFirst() {
let slice = self[start...end]
if try !isMember(slice, self[end]) {
result.append(self[start..<end])
start = end
}
}
if start != self.endIndex {
result.append(self[start..<self.endIndex])
}
return result
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment