Accumulating the results of a generator

Is there a way to accumulate the results of a generator? I have a block like this:

i = {
  for (let i = 0; i < 10; i++) {
    yield i;
  }
}

and I’d like to be able to collect all of the values yielded from the block in an Array:

[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

The use case is for replaying all of the intermediate states of an algorithm.

I was going to write an inline response in the forum, but it became easier to write a notebook so that the examples are runnable. Perhaps one day we’ll be able to use Observable notebooks in our forums, but for now, here’s a link:

https://beta.observablehq.com/@mbostock/accumulating-a-generator

3 Likes

Thanks, @mbostock.

Using cells as reducers. :exploding_head: :heart_eyes: So cool.

Thanks for this. I used some techniques from your notebook to inform how I built out my haiku generator.

:clap:

I was using the “return array” trick, but I wonder if there would be a performance issue if I were to, say, plot all the numbers (a lot of them) and it keeps having to redraw everything.

The spread operator is not really “reactive”, only giving the full array at the end.