Skip to content

Instantly share code, notes, and snippets.

@justinmeiners
Last active March 7, 2022 21:47
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 justinmeiners/ab87e47e5f6fd1451d29d5bb29b6beaf to your computer and use it in GitHub Desktop.
Save justinmeiners/ab87e47e5f6fd1451d29d5bb29b6beaf to your computer and use it in GitHub Desktop.
enum CollectionMultiplicity<C: Collection> {
case none
case one(first: C.Index)
case many(first: C.Index, second: C.Index)
}
extension Collection {
func indexedMultiplicity(where predicate: (Element) -> Bool) -> CollectionMultiplicity<Self> {
guard let i = firstIndex(where: predicate) else {
return .none
}
guard let j = suffix(from: index(after: i)).firstIndex(where: predicate) else {
return .one(first: i)
}
return .many(first: i, second: j)
}
}
enum SequenceMultiplicity<S: Sequence> {
case none
case one(first: S.Element)
case many(first: S.Element, second: S.Element)
}
extension Sequence {
func multiplicity(where predicate: (Element) -> Bool) -> SequenceMultiplicity<Self> {
var it = makeIterator()
while let x = it.next() {
if predicate(x) {
while let y = it.next() {
if predicate(y) {
return .many(first: x, second: y)
}
}
return .one(first: x)
}
}
return .none
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment