Check out Dart's iterators

Domenic Denicola domenic at domenicdenicola.com
Sat Feb 9 23:54:25 PST 2013


I know `StopIteration` is pretty baked in by now. But, most of the arguments I can recall for it are that it’s better than `hasNext` + `next`, wherein you have to keep two methods in sync. I saw the Dart iterator API the other day and it provided a third alternative I thought the list might enjoy contemplating:

https://www.dartlang.org/articles/m3-whats-new/iterables.html#iterator

Translated to ES6, an iterable that counts to 5 it would look like:

import { current, next } from "@iter";

let iterable = {
  [next]() {
    if (this[current] < 5) {
      this[current]++;
    }
    return this[current] <= 5;
  },
  [current]: 0
};

That is, `next` does all the work, returning `true`/`false` to signal whether the iteration should proceed. It then keeps `current` in sync with the current value.

Interesting, if perhaps too late for ES6. I'd of course love to hear why `StopIteration` is better than this, so I can understand and defend it better.


More information about the es-discuss mailing list