Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to restart iteration with Map.values() method?

I want to restart iteration after the iterator reaches to done state.
Just look at the example:

const newMap = new Map<string, string>([
  ['key1', 'value1'],
  ['key2', 'value2']
]);

const iterator = newMap.values() // It can be newMap.entries()

iterator.next().value   // prints value1
iterator.next().value    //prints value2
iterator.next().value //prints undefined

I just want something like:

iterator.restart();
iterator.next().value // prints value1

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You could craft your own iterator that, when asked to, calls newMap.values() again:

const newMap = new Map([
  ['key1', 'value1'],
  ['key2', 'value2']
]);

const myIterator = (() => {
  let currentIterator = newMap.values();
  
  return {
    next() {
      return currentIterator.next();
    },
    restart() {
      currentIterator = newMap.values();
    }
  }
})()
console.log(myIterator.next().value)   // prints value1
console.log(myIterator.next().value)    //prints value2
console.log(myIterator.next().value) //prints undefined

myIterator.restart();
console.log(myIterator.next().value) // prints value1
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading