Cycle through array with JavaScript

Easily cycle through array elements with function generators.

2022-07-27
frontend
javascript
Share on

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

Seems like the easiest way to construct a function that will do that is with a function generator:

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