All files / collections / unstable_cycle.ts

100.00% Branches 4/4
100.00% Lines 11/11
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
x2
x7
 
x7
x45
x45
x55
x45
x73
x96
x45
x7








































// Copyright 2018-2025 the Deno authors. MIT license.

/**
 * Creates an iterator that cycles indefinitely over the provided iterable.
 *
 * Each time the iterable is exhausted, a new iterator is obtained to start the cycle again.
 * This generator will yield the values from the iterable continuously.
 *
 * > **Note:** If the iterable is empty, the generator will keep restarting and yield nothing.
 *
 * @typeParam T The type of the elements in the iterable.
 * @param iterable The iterable whose values are to be cycled.
 * @returns A generator that yields values from the iterable in an endless cycle.
 *
 * @example Basic usage
 * ```ts
 * import { cycle } from "@std/collections/unstable-cycle";
 * import { assertEquals } from "@std/assert";
 *
 * const cyclic = cycle([1, 2, 3]);
 * const result: number[] = [];
 *
 * for (const num of cyclic) {
 *   result.push(num);
 *   if (result.length === 7) break;
 * }
 *
 * assertEquals(result, [1, 2, 3, 1, 2, 3, 1]);
 * ```
 */
export function* cycle<T>(iterable: Iterable<T>): Generator<T> {
  let iterator = iterable[Symbol.iterator]();

  while (true) {
    const result = iterator.next();
    if (result.done) {
      iterator = iterable[Symbol.iterator]();
    } else {
      yield result.value;
    }
  }
}