0

So I have a javascript generator (below) which continues to yield random numbers ad infinitum.

function* createRandomNumberStream(): IterableIterator<number> {
  while (true) {
    yield Math.random()
  }
}

How can I write a generator function with the type (it: Iterable<T>, n: number) => Iterable<T>, where it returns a new iterable which ends after n yields?

Note the createRandomStream() generator isn't really relevant, it's just an example of an unending iterable generator. I'm trying to make a generator which basically slices an iterable.

James Jensen
  • 518
  • 6
  • 19
  • I believe you need [itertools.islice](https://docs.python.org/3/library/itertools.html#itertools.islice) – Hamms Feb 18 '20 at 23:49
  • Does this answer your question? [How to slice a generator object or iterator in Python](https://stackoverflow.com/questions/34732311/how-to-slice-a-generator-object-or-iterator-in-python) – Hamms Feb 18 '20 at 23:49
  • @Hamms apologies for the confusion, this is a javascript/typescript question, not python. – James Jensen Feb 18 '20 at 23:50
  • oh, my apologies – Hamms Feb 19 '20 at 00:03
  • [Some good usable examples](https://github.com/vitaly-t/prime-lib/blob/main/src/utils.ts). – vitaly-t Nov 10 '22 at 00:30

1 Answers1

2

Is this what you want?

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)
}
Asaf Aviv
  • 11,279
  • 1
  • 28
  • 45