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