Skip to content

Instantly share code, notes, and snippets.

@khanlou
Created September 30, 2018 01:15
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 khanlou/366da3e2cdfcbfe8b32d6ed7649ada7f to your computer and use it in GitHub Desktop.
Save khanlou/366da3e2cdfcbfe8b32d6ed7649ada7f to your computer and use it in GitHub Desktop.
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