2022 / 07 / 27
Cycle through array with JavaScript

Easily cycle through array elements with function generators.

frontend
javascript

Let’s say you have an array and you’d like to cycle through its elements over and over. How would you go about it?

Let’s try with function generators, shall we?

function* cycleThrough(someArray) {
  while (true) yield* someArray
}

You can use it like this:

function* cycleThrough(someArray) {
  while (true) yield* someArray
}

const sortDirection = ['ASC', 'DESC', null]
const gen = cycleThrough(sortDirection)

console.log(gen.next().value) // 'ASC'
console.log(gen.next().value) // 'DESC'
console.log(gen.next().value) // null
console.log(gen.next().value) // 'ASC'

I know there are several ways to approach this problem, but I found this one the easiest and simplest way to construct a function that can iterate indefinitely over any array.

References