Menu

gitpiper

cycleGenerator javascript Code Snippet in 2024

functiongeneratoradvanced

Last Updated: 16 December 2024

Creates a generator, looping over the given array indefinitely.

  • Use a non-terminating while loop, that will yield a value every time Generator.prototype.next() is called.
  • Use the module operator (%) with Array.prototype.length to get the next value's index and increment the counter after each yield statement.
const cycleGenerator = function* (arr) { let i = 0; while (true) { yield arr[i % arr.length]; i++; } };
const binaryCycle = cycleGenerator([0, 1]); binaryCycle.next(); // { value: 0, done: false } binaryCycle.next(); // { value: 1, done: false } binaryCycle.next(); // { value: 0, done: false } binaryCycle.next(); // { value: 1, done: false }

javascript snippet similar to cycleGenerator For You in December 2024

Subscribe to our Newsletter

Subscribe to get resources directly to your inbox. You won't receive any spam! ✌️

© 2024 GitPiper. All rights reserved

Rackpiper Technology Inc

Company

About UsBlogContact

Subscribe to our Newsletter

Subscribe to get resources directly to your inbox. You won't receive any spam! ✌️