所以我有一个javascript生成器(如下图所示),它可以无限地产生随机数。
function* createRandomNumberStream(): IterableIterator<number> {
while (true) {
yield Math.random()
}
}如何编写类型为(it: Iterable<T>, n: number) => Iterable<T>的生成器函数,其中返回一个新的迭代器,该迭代器在n之后结束?
注意,createRandomStream()生成器并不是真正相关的,它只是一个无休止的可迭代生成器的示例。我正在尝试制作一个生成器,它基本上对一个迭代器进行切片。
发布于 2020-02-19 08:14:48
这是你想要的吗?
function* createRandomNumberStream() {
while (true) {
yield Math.random()
}
}
function* take<T>(it: Iterator<T>, count: number) {
let currentCount = 0
while (currentCount++ < count) {
yield it.next().value
}
}
const stream = take(createRandomNumberStream(), 3)
for (const num of stream) {
console.log(num)
}https://stackoverflow.com/questions/60291035
复制相似问题