lobo_tuerto's notes
Home
Blog
Notes
About

Cycle through array with JavaScript

Easily cycle through array elements with function generators.

📅Published27 July 2022
🏷️
frontendjavascript

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


Got comments or feedback?
Follow me on
v-3ab054c