iterable-iterator/cycle Home Manual Reference Source

src/ncycle.js

  1. /**
  2. * Same as {@link cycle} but only cycles a limited number of times.
  3. *
  4. * @example
  5. * // returns [0,1,0,1,0,1,0,1]
  6. * list(ncycle(range(2),4)) ;
  7. *
  8. * @param {Iterable} iterable - The input iterable.
  9. * @param {Number} n - The number of times to cycle through the input iterable.
  10. * @returns {Iterator}
  11. *
  12. */
  13. export default function* ncycle(iterable, n) {
  14. const buffer = [];
  15.  
  16. for (const item of iterable) {
  17. yield item;
  18. buffer.push(item);
  19. }
  20.  
  21. if (buffer.length === 0) {
  22. return;
  23. }
  24.  
  25. while (--n > 0) {
  26. yield* buffer;
  27. }
  28. }