Created
November 7, 2018 23:35
-
-
Save khanlou/f83d750acb45c71c62ec99559c472b89 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