Last active
March 7, 2022 21:47
-
-
Save justinmeiners/ab87e47e5f6fd1451d29d5bb29b6beaf to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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