cycle method

Iterable<T> cycle([
  1. int n = 0
])

Creates an iterable that cycles through the elements of this iterable.

If n is provided and greater than 0, the returned iterable cycles through the elements of this iterable n times. If n is 0 or not provided, the iterable cycles infinitely.

Parameters: n (int, optional): The number of times to cycle through the iterable. Defaults to 0, indicating an infinite cycle.

Returns: Iterable

Example:

List<int> numbers = [1, 2, 3];
Iterable<int> cycledNumbers = numbers.cycle(2); // Cycles through [1, 2, 3, 1, 2, 3]

Note: The returned iterable is lazy. Elements are only processed as they are iterated over.

Implementation

Iterable<T> cycle([int n = 0]) sync* {
  if (isEmpty) return;

  if (n <= 0) {
    // Infinite cycle
    while (true) {
      for (var element in this) {
        yield element;
      }
    }
  } else {
    // Cycle n times
    for (int i = 0; i < n; i++) {
      for (var element in this) {
        yield element;
      }
    }
  }
}