试着把头包裹在发电机周围而我却找不到它。
我有一个名为KeyGen
的简单非生成器迭代器类,我想用JS generators重写:
如果这不是生成器的假设,那么请发表评论,我将关闭
class KeyGen {
constructor(numOfKeys) {
this.keys = new Array(numOfKeys).fill(0).map((i, index) => index);
this.iteratorCount = 0;
}
keyIterator() {
return {
next: () => this.keys[this.iteratorCount++]
}
}
}
const keyGen = new KeyGen(4);
console.log(keyGen.keyIterator().next());
console.log(keyGen.keyIterator().next());
console.log(keyGen.keyIterator().next());
console.log(keyGen.keyIterator().next());
答案 0 :(得分:2)
这很简单,只需声明数组,然后yield
每个元素:
function* gen(length) {
const keys = Array.from({ length }, (_, i) => i);
for (const key of keys) yield key;
}
const iter = gen(3);
console.log(iter.next().value);
console.log(iter.next().value);
console.log(iter.next().value);
答案 1 :(得分:1)
这里的生成器非常合适,但您应该注意原始代码与生成器不同。对于生成器,next
调用应返回包含两个键value
和done
的对象。
要转换为生成器函数,您只需构建初始列表以与现在相同的方式进行迭代,但是您可以逐个使用常规for循环来逐个yield
每个元素
示例:
function* KeyGen(numOfKeys) {
const keys = Array(numOfKeys)
.fill(0)
.map((i, index) => index);
for (let key of keys) {
yield key;
}
}
const keyGen = KeyGen(4);
console.log(keyGen.next())
console.log(keyGen.next())
console.log(keyGen.next())
console.log(keyGen.next())
console.log(keyGen.next())
// For extra coolness, note that for/of loops are designed to work with generators:
for (let key of KeyGen(4)) {
console.log(key)
}