Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
struct LazyUniquedSequence<Element>: Sequence {
let base: AnySequence<Element>
let isEqual: (Element, Element) -> Bool
init<S: Sequence>(_ sequence: S, isEqual: @escaping (Element, Element) -> Bool) where S.Element == Element {
self.base = AnySequence(sequence)
self.isEqual = isEqual
}
func makeIterator() -> AnyIterator<Element> {
var seen: [Element] = []
let iterator = base.makeIterator()
return AnyIterator({
while let next = iterator.next() {
if !seen.contains(where: { self.isEqual($0, next) }) {
seen.append(next)
return next
}
}
return nil
})
}
}
extension LazySequenceProtocol where Elements.Element: Equatable {
func uniqued() -> LazyUniquedSequence<Element> {
return LazyUniquedSequence(self, isEqual: ==)
}
}
extension LazySequenceProtocol {
func uniqued(by isEqual: @escaping (Element, Element) -> Bool) -> LazyUniquedSequence<Element> {
return LazyUniquedSequence(self, isEqual: isEqual)
}
}
let thing = AnySequence([1, 1, 1, 1, 2, 2, 2, 2, 3, -1, 2, 4, -1])
.lazy
.map({ int -> String in print("doing\(int)"); return String(int) })
.uniqued()
thing.forEach({ print($0) })
print("done")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.