Iterators can be hard to work with for beginners

Just a comment from my first days of working with cm6, coming from cm5:

Overall my first experience was pretty smooth, the documentation is really nice, but one hurdle was working with the iterator types, like RangeSet.iter (my use case was iterating through all widgets) and TextIterator (iterating through lines of a document).

It took me some time to realise that these are not ES6 iterators, which is why Array.from(iterator) returns the empty array, and [...iterator] throws an error.

Is anyone else facing these problems? Some ideas that might help:

  • More clearly document the difference with ES6 iterators, and give examples of how to work with them.
  • Implement a .toArray() function.

TextIterators are CM6 iterators. It’s just that Array.from takes an iterable, not an iterator, which is a little awkward. This patch fixes that.

The RangeCursor docs say right there that this isn’t an ES6 iterator. For practical reasons, those don’t have a non-started state and don’t conform to the ES6 protocols.

1 Like

Awesome, thank you! Would you be interested in a PR that adds a toArray function to the RangeCursor interface?

I’m not sure converting range cursors to arrays is a useful/common enough thing to warrant a specialized method. What are you doing that requires it?

I have inline widgets that can change their look when the global state changes:

So on a state change, I am sending this new state to all inline widgets. My current solution iterates over all widgets in the editor, which is stored as a DecorationSet.

I think I should spend some more time with the documentation and examples before you spend too much time on this though! Thanks for the help so far

Widgets can’t really be mutable objects though. Wouldn’t the between method be more practical for that? You don’t want ranges, you want the actual decorations.

Apologies for reviving an old topic, but would it be possible to make ChangeSet.iterChanges and iterChangedRanges return a regular ES2015 iterator as well?

That’d involve quite a bit more code (since the codebase doesn’t use generators), and I’ve never needed external iterators on those so far.