Skip to content

Instantly share code, notes, and snippets.

@natecook1000
Created August 25, 2017 20:57
Show Gist options
  • Select an option

  • Save natecook1000/c367ffdbb9afd351f3bd5bd2446d44c8 to your computer and use it in GitHub Desktop.

Select an option

Save natecook1000/c367ffdbb9afd351f3bd5bd2446d44c8 to your computer and use it in GitHub Desktop.
extension Collection {
func sliced(
where predicate: (Element, Element) -> Bool
) -> [SubSequence] {
var result: [SubSequence] = []
var start = startIndex
for (i, j) in zip(indices, indices.dropFirst()) {
if predicate(self[i], self[j]) {
result.append(self[start..<j])
start = j
}
}
result.append(self[start...])
return result
}
}
[1, 1, 2, 2, 2, 3, 4, 4].sliced(where: !=)
// [[1, 1], [2, 2, 2], [3], [4, 4]]
[1, 1, 1, 1, 1, 1, 1].sliced(where: !=)
// [[1, 1, 1, 1, 1, 1, 1]]
[1, 2, 3, 1, 1, 2, 3, 2, 5, 4, 7, 8, 9].sliced(where: >)
// [[1, 2, 3], [1, 1, 2, 3], [2, 5], [4, 7, 8, 9]]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment