Created
May 3, 2022 10:53
-
-
Save masakih/e369b41f9e53eec2be051679f6d51790 to your computer and use it in GitHub Desktop.
骨が出来た #CodePiece
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 JoinedCollection<C1: Collection, C2: Collection, Element>: Collection | |
| where C1.Element == Element, C2.Element == Element, C1.Index == Int, C2.Index == Int { | |
| var left: C1 | |
| var right: C2 | |
| init(_ left: C1, _ right: C2) { | |
| self.left = left | |
| self.right = right | |
| } | |
| /// Sequence | |
| struct Iterator: IteratorProtocol { | |
| var iter1: C1.Iterator | |
| var iter2: C2.Iterator | |
| init(_ c: JoinedCollection) { | |
| self.iter1 = c.left.makeIterator() | |
| self.iter2 = c.right.makeIterator() | |
| } | |
| mutating func next() -> Element? { | |
| if let e = iter1.next() { | |
| return e | |
| } | |
| return iter2.next() | |
| } | |
| } | |
| func makeIterator() -> Iterator { | |
| return Iterator(self) | |
| } | |
| /// Collection | |
| var startIndex: Int { | |
| left.startIndex | |
| } | |
| var endIndex: Int { | |
| left.endIndex + right.endIndex | |
| } | |
| func index(after i: Int) -> Int { | |
| i + 1 | |
| } | |
| subscript(_ i: Int) -> Element { | |
| if i < left.endIndex { | |
| return left[i] | |
| } | |
| return right[i - left.endIndex] | |
| } | |
| } | |
| extension JoinedCollection: BidirectionalCollection | |
| where C1: BidirectionalCollection, C2: BidirectionalCollection { | |
| func index(before i: Int) -> Int { | |
| i - 1 | |
| } | |
| } | |
| extension JoinedCollection: RandomAccessCollection | |
| where C1: RandomAccessCollection, C2: RandomAccessCollection {} | |
| extension JoinedCollection { | |
| init<C3, C4>(_ c1: C1, _ c3: C3, _ c4: C4) | |
| where C2 == JoinedCollection<C3, C4, Element> { | |
| self.left = c1 | |
| self.right = .init(c3, c4) | |
| } | |
| init<C3, C4, C5, C6>(_ c3: C3, _ c4: C4, _ c5: C5, _ c6: C6) | |
| where C1 == JoinedCollection<C3, C4, Element>, C2 == JoinedCollection<C5, C6, Element> { | |
| self.left = .init(c3, c4) | |
| self.right = .init(c5, c6) | |
| } | |
| } | |
| let j01 = JoinedCollection([], [3, 4, 5]) | |
| print(j01) | |
| print("\nCount: ", j01.count) | |
| print("\nElements:") | |
| j01.forEach { print($0) } | |
| print("\nIndex Access:", j01[2]) | |
| print("\nReserved:") | |
| j01.reversed().forEach { print($0) } | |
| let j02 = JoinedCollection([0, 1, 2], [10, 11, 12, 13], [20, 21, 22, 23, 24]) | |
| print(j02) | |
| print("\nCount: ", j02.count) | |
| print("\nElements:") | |
| j02.forEach { print($0) } | |
| print("\nIndex Access:", j02[2], j02[4], j02[8]) | |
| print("\nReserved:") | |
| j02.reversed().forEach { print($0) } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment