Skip to content

Instantly share code, notes, and snippets.

@raganwald
Created June 26, 2017 21:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save raganwald/2908753f6d0192c3ead0dac62d2cb469 to your computer and use it in GitHub Desktop.
Save raganwald/2908753f6d0192c3ead0dac62d2cb469 to your computer and use it in GitHub Desktop.
I'm very confoosed
// 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
@raganwald
Copy link
Author

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