'How do I cycle through an array when I call a method?

const directions = ["North", "West", "South", "East"];

I want directions.next(); to cycle through them in order. How do I accomplish that in the latest iteration of the ECMAScript? I want every function that calls for directions to get what .next() established to be next.

Does it need to be its own mini-data structure?

Here's what I want to accomplish:

`["Jason Bourne", "Foma Kinaev", "John Michael Kane"]`.next() # // Jason Bourne
`["Jason Bourne", "Foma Kinaev", "John Michael Kane"]`.next() # // Foma Kinaev
`["Jason Bourne", "Foma Kinaev", "John Michael Kane"]`.next() # // John Michael Kane
`["Jason Bourne", "Foma Kinaev", "John Michael Kane"]`.next() # // Jason Bourne


Solution 1:[1]

JavaScript arrays don't maintain any iteration state so you'd need to handle some form of internal index pointer yourself

const directions = ["North", "West", "South", "East"];

Array.prototype._current = 0
Array.prototype.next = function() {
  const cur = this[this._current]
  this._current = (this._current + 1) % this.length
  return cur
}

console.log(directions.next())
console.log(directions.next())
console.log(directions.next())
console.log(directions.next())
console.log(directions.next())

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Phil