Always close iterators?

Axel Rauschmayer axel at rauschma.de
Wed Mar 25 16:31:41 UTC 2015


Given that redundant calls to `return()` don’t make a difference (h/t Bergi), wouldn’t the iteration protocol be simpler if iterators were always closed (versus only if iteration finishes abruptly). The code of generators wouldn’t change (`finally` etc.), but “manually implemented” iterators could be written without the check in line (A). They’d become simpler and more similar to generators and `finally`.

```js
let iterable = {
    [Symbol.iterator]() {
        return {
            next() {
                if (iterationIsDone()) {
                    return { done: true };
                } else {
                    let result = { value: nextValue(), done: false };
                    if (iterationIsDone()) { // (A)
                         cleanUp();
                    }
                    return result;
                }
            },
            return(value) {
                if (! iterationIsDone()) {
                    cleanUp();
                }
                return { value: value, done: true };
            }
        }
    }
}
```

-- 
Dr. Axel Rauschmayer
axel at rauschma.de
rauschma.de



-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.mozilla.org/pipermail/es-discuss/attachments/20150325/1e2e0467/attachment.html>


More information about the es-discuss mailing list