Home > Software design >  How do I cycle through an array when I call a method?
How do I cycle through an array when I call a method?

Time:02-24

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

CodePudding user response:

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())

CodePudding user response:

You could use a generator function to yield the values of your array continuously in a while loop (to enabled circular iteration). Then use the generator to give you an iterator that you can then call .next() on to grab the value:

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

function* getItr(arr) {
  while(true) yield* arr;
}

const itr = getItr(directions);
console.log(itr.next().value); // North
console.log(itr.next().value); // West
console.log(itr.next().value); // South
console.log(itr.next().value); // East
console.log(itr.next().value); // North

  • Related