简体   繁体   English

Javascript 中的 Python itertools 循环等效项是什么?

[英]What is the Python itertools cycle equivalent in Javascript?

I could not find an equivalent function of Python cycle in itertools:我在 itertools 中找不到 Python 循环的等效 function 循环:

from itertools import cycle
g = cycle(('a','b'))
next(g) # a
next(g) # b
next(g) # a
# etc. etc.

in Javascript.在 Javascript 中。

The goal is to create an infinite cycle in an array of values.目标是在一组值中创建一个无限循环。 I guess I could use a Javascript generator but I was wondering if there is any built-in function.我想我可以使用 Javascript 生成器,但我想知道是否有任何内置的 function。

There is no built in functionality for this.没有内置功能。 With that said, it is easy to make a function that accepts any number of arguments and cycles through them:话虽如此,很容易制作一个接受任意数量的 arguments 并循环遍历它们的 function:

 function* cycle(...items) { while(true) yield* items; } const gen = cycle("a", "b"); console.log(gen.next().value); console.log(gen.next().value); console.log(gen.next().value);

This uses yield* to delegate to the iterator of the array items , effectively yield* items;这使用yield*委托给数组items的迭代器,有效地yield* items; is a shorter version of是一个较短的版本

for (const item of items)
  yield item;

Alternatively, it can accept an array and continually cycle through its contents或者,它可以接受一个数组并不断循环其内容

 function* cycle(items) { while(true) yield* items; } const gen = cycle(["a", "b"]); console.log(gen.next().value); console.log(gen.next().value); console.log(gen.next().value);

If it has to support any iterables passed in, it will have to maintain a chache of the first iteration, so it can repeat the further cycles.如果它必须支持传入的任何迭代,它必须维护第一次迭代的 chache,以便它可以重复进一步的循环。 I have shown an implementation of this in this answer of mine .我已经在我的这个答案中展示了这个实现。 Here is the implementation:这是实现:

 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


There is a proposal called Iterator helpers which aims to add tools similar to itertools and, in general, ease the use of iterators.有一个名为Iterator helpers的提议,旨在添加类似于 itertools 的工具,并且通常简化迭代器的使用。 The proposal is currently in stage 2 out of 4 in the approval process.该提案目前处于批准过程中的第 4 阶段中的第 2 阶段。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM