Search code examples
javascripttypescriptyielditerable

How to create a finite length generator from an infinite generator


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.


Solution

  • 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)
    }