Skip to content

Commit b4d0636

Browse files
committed
Implement FiniteCycle with Iterator wrapper around Product2 Iterator.
1 parent c636b09 commit b4d0636

File tree

1 file changed

+41
-0
lines changed

1 file changed

+41
-0
lines changed

Sources/Algorithms/Cycle.swift

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -56,6 +56,47 @@ extension Cycle: Sequence {
5656

5757
extension Cycle: LazySequenceProtocol where Base: LazySequenceProtocol {}
5858

59+
60+
/// A collection wrapper that repeats the elements of a base collection for a finite number of times.
61+
public struct FiniteCycle<Base: Collection> {
62+
/// The collection to repeat.
63+
public let base: Base
64+
65+
/// The number of times to repeat the collection.
66+
public let times: Int
67+
68+
@usableFromInline
69+
internal init(base: Base, times: Int) {
70+
self.base = base
71+
self.times = times
72+
}
73+
}
74+
75+
extension FiniteCycle: Sequence {
76+
/// The iterator for a `FiniteCycle` sequence.
77+
public struct Iterator : IteratorProtocol {
78+
@usableFromInline
79+
var productIterator: Product2<Range<Int>, Base>.Iterator
80+
81+
@usableFromInline
82+
internal init(_ product: Product2<Range<Int>, Base>) {
83+
self.productIterator = product.makeIterator()
84+
}
85+
86+
@inlinable
87+
public mutating func next() -> Base.Element? {
88+
self.productIterator.next()?.1
89+
}
90+
}
91+
92+
public func makeIterator() -> Iterator {
93+
let iterations: Range<Int> = 0..<times
94+
return Iterator(Product2(iterations, base))
95+
}
96+
}
97+
98+
extension FiniteCycle: LazySequenceProtocol where Base: LazySequenceProtocol {}
99+
59100
//===----------------------------------------------------------------------===//
60101
// cycled()
61102
//===----------------------------------------------------------------------===//

0 commit comments

Comments
 (0)