Created
September 22, 2017 20:59
-
-
Save natecook1000/66d6cbfa5ed5d355aa1dbd003d363c5e 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 LazySplitSequence<Base: Sequence> : Sequence, LazySequenceProtocol { | |
| struct Iterator : IteratorProtocol { | |
| mutating func next() -> [Base.Element]? { | |
| var result: [Base.Element] = [] | |
| if splits == 0 { | |
| while let element = iterator.next() { | |
| result.append(element) | |
| } | |
| return result.isEmpty ? nil : result | |
| } | |
| splits -= 1 | |
| var iterated = false | |
| while let element = iterator.next() { | |
| iterated = true | |
| if separator(element) { | |
| if omittingEmptySubsequences && result.isEmpty { | |
| continue | |
| } | |
| break | |
| } | |
| result.append(element) | |
| } | |
| return iterated | |
| ? result | |
| : nil | |
| } | |
| var iterator: Base.Iterator | |
| var splits: Int | |
| let omittingEmptySubsequences: Bool | |
| let separator: (Base.Element) -> Bool | |
| } | |
| func makeIterator() -> Iterator { | |
| return Iterator(iterator: base.makeIterator(), splits: maxSplits, omittingEmptySubsequences: omittingEmptySubsequences, separator: separator) | |
| } | |
| var base: Base | |
| let maxSplits: Int | |
| let omittingEmptySubsequences: Bool | |
| let separator: (Base.Element) -> Bool | |
| } | |
| extension LazySequenceProtocol { | |
| func split(maxSplits: Int = Int.max, omittingEmptySubsequences: Bool = true, whereSeparator isSeparator: @escaping (Element) -> Bool) -> LazySplitSequence<Self> { | |
| return LazySplitSequence(base: self, maxSplits: maxSplits, omittingEmptySubsequences: omittingEmptySubsequences, separator: isSeparator) | |
| } | |
| } | |
| extension LazySequenceProtocol where Element: Equatable { | |
| func split(separator: Element, maxSplits: Int = Int.max, omittingEmptySubsequences: Bool = true) -> LazySplitSequence<Self> { | |
| return LazySplitSequence(base: self, maxSplits: maxSplits, omittingEmptySubsequences: omittingEmptySubsequences, separator: { $0 == separator }) | |
| } | |
| } | |
| let a = [1, 2, 3, 3, 3, 4, 5, 6, 7, 8] | |
| print(a.split { $0 % 3 == 0 }) | |
| let s = a.lazy.split { $0 % 3 == 0 } | |
| print(s) | |
| for b in s { | |
| print(b) | |
| } | |
| // ambiguous :/ | |
| // let s2 = a.lazy.split(separator: 3) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment