Created
June 26, 2017 21:00
-
-
Save raganwald/2908753f6d0192c3ead0dac62d2cb469 to your computer and use it in GitHub Desktop.
I'm very confoosed
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// How does this iterable ever become "done?" | |
function * Numbers () { | |
let n = 0; | |
while (true) yield n++; | |
} | |
const numbers = Numbers(); | |
// 1. I expect 'true', I don't expect it to iterate to infinity | |
const [first] = numbers; | |
console.log(first); | |
//=> 0 | |
// 2. I expect it to iterate from 1 to infinity with the "unused" | |
// elements of the iterator. Or maybe iterate from 0. | |
// I do not expect nothing. | |
for (const number of numbers) { | |
console.log(number); | |
} | |
//=> outputs nothing, does not iterate to infinity | |
const numbers_iterator = numbers[Symbol.iterator](); | |
// 3. I do not expect .done to return `true`, | |
// Clearly, using an iterator for pattern matching tells the generator | |
// function that it is done, and forces it to "return." | |
console.log(numbers_iterator.next().done) | |
//=> true |
Yes!
I had forgotten that destructuring also followed this pattern of cleaning up resources it doesn't "own," which I will tactfully not say is wrong or right, just point out that it is not my cup of tea. I think it is part of a much larger conundrum related to protocols for memory management. Which code has the responsibility for disposing of objects in a system without automatic garbage collection?
One solution I've seen to avoid this problem is a pattern I saw in @rauschma's book, namely to wrap iterators in a "condom" that blocks .return(...)
. Maybe you cover this as well?
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Both looping and destructuring call 'return()' on the iterator when they complete... supposedly because makers of iterators want to be able to "clean up" resources in their 'finally' clauses.
I understood the case for doing this with loops and '...' operator, but I strongly disagreed with doing it for destructuring and I argued against it. They did it anyway mostly for symmetry sake it seems. :(