Skip to content

Commit

Permalink
feat(transducers): add opt limit for cycle()
Browse files Browse the repository at this point in the history
  • Loading branch information
postspectacular committed Jan 13, 2020
1 parent 31bd5b9 commit 186daff
Showing 1 changed file with 14 additions and 3 deletions.
17 changes: 14 additions & 3 deletions packages/transducers/src/iter/cycle.ts
Original file line number Diff line number Diff line change
@@ -1,23 +1,34 @@
/**
* Iterator which yields an infinite repetition of given `input`
* iterable's values. Produces no values if `input` is empty.
* iterable's values. Produces no values if `input` is empty. If `num`
* is given, only that many cycles will be emitted.
*
* @remarks
* Also see {@link repeat}, {@link repeatedly} for related functions.
*
* @example
* ```ts
* // take 5 from infinite sequence
* [...take(5, cycle([1, 2, 3]))]
* // [1, 2, 3, 1, 2]
*
* // only produce 2 cycles
* [...cycle(range(3), 2)]
* // [ 0, 1, 2, 0, 1, 2 ]
* ```
*
* @param input -
* @param num -
*/
export function* cycle<T>(input: Iterable<T>) {
export function* cycle<T>(input: Iterable<T>, num = Infinity) {
if (num < 1) return;
let cache: T[] = [];
for (let i of input) {
cache.push(i);
yield i;
}
if (cache.length > 0) {
while (true) {
while (--num > 0) {
yield* cache;
}
}
Expand Down

0 comments on commit 186daff

Please sign in to comment.