如何使用 Map.values() 方法重新开始迭代?

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

我想在迭代器达到完成状态后重新开始迭代。 只看例子:

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

我只想要这样的东西:

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

再次调用 .values(或任何方法)。

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

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

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

iterator = newMap.values()
console.log(iterator.next().value) // prints value1

迭代器不可重用 - 每次你想从头开始时都必须重新创建它们。

如果你想要无休止地重复值,你可以制作一个生成器函数,第一次缓存这些值,然后永远从头开始给你缓存:

function* repeat(iterable) {
  const cache = [];
  
  //lazily supply the values from the iterable while caching them
  for (const next of iterable) {
    cache.push(next);
    yield next;
  }
  
  //delegate to the cache at this point
  while(true)
    yield* cache;
}

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

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

console.log(iterator.next().value) // prints value1
console.log(iterator.next().value) // prints value2
console.log(iterator.next().value) // prints value1
console.log(iterator.next().value) // prints value2
console.log(iterator.next().value) // prints value1
console.log(iterator.next().value) // prints value2

或者,如果您不想缓存,您可以通过采用一个可迭代的函数来简化 repeat() 实现。任何时候你调用它,你都会得到一个新的并永远委托给它:

function* repeat(iterableSupplier) {
  //delegate to the value from the supplier
  while(true)
    yield* iterableSupplier();
}

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

const iterator = repeat(() => newMap.values()) // It can be newMap.entries()
//    give a function   ^^^^^

console.log(iterator.next().value) // prints value1
console.log(iterator.next().value) // prints value2
console.log(iterator.next().value) // prints value1
console.log(iterator.next().value) // prints value2
console.log(iterator.next().value) // prints value1
console.log(iterator.next().value) // prints value2

查看更多关于:

您可以制作自己的迭代器,当被要求时,再次调用 newMap.values():

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