cycle

import { cycle } from "jsr:@ende/collections/unstable-cycle";

function ยท experimental

function* cycle<T>(iterable: Iterable<T>): Generator<T>

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.

iterable: Iterable<T>

The iterable whose values are to be cycled.

Returns

A generator that yields values from the iterable in an endless cycle.

Example: Basic usage

import { cycle } from "@ende/collections/unstable-cycle";
import { assertEquals } from "@ende/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]);

Source