How do I implement a cycle-through array with a generator function How do I implement a cycle-through array with a generator function typescript typescript

How do I implement a cycle-through array with a generator function


You need a loop in your generator code, otherwise there is only one yield happening:

function* stepGen(steps){  let index = 0;  while (true) {    yield steps[index];    index = (index+1)%steps.length;  }}let gen = stepGen(['one', 'two', 'three']); // pass array to make it more reusableconsole.log(gen.next().value); console.log(gen.next().value);console.log(gen.next().value);console.log(gen.next().value);console.log(gen.next().value);

Alternatively you can also use yield* which yields values from an iterable, one by one:

function* stepGen(steps){  while (true) yield* steps;}let gen = stepGen(['one', 'two', 'three']);console.log(gen.next().value); console.log(gen.next().value);console.log(gen.next().value);console.log(gen.next().value);console.log(gen.next().value);