Created
June 3, 2025 16:33
-
-
Save rauschma/ac3133b5814a8b3d09e833df062b0d1d to your computer and use it in GitHub Desktop.
Revisions
-
rauschma created this gist
Jun 3, 2025 .There are no files selected for viewing
This file contains hidden or 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 charactersOriginal file line number Diff line number Diff line change @@ -0,0 +1,44 @@ # Creating synchronous iterators [The methods of class `Iterator`](https://2ality.com/2022/12/iterator-helpers.html) let us process data incrementally. Let’s explore where we can use them. ##### Getting iterators from iterables * `Iterator.from(iterable)` always returns instances of `Iterator` (converting non-instances to instances as needed). * `iterable[Symbol.iterator]()` returns an iterator: * With all built-in data structures, the result is an instance of `Iterator`. * With other, older iterable objects, the result may not be an instance of `Iterator`. ##### Built-in methods that return iterators Arrays, Typed Arrays, Sets and Maps have additional methods that return iterators: * Arrays (similarly: Typed Arrays): * `Array.prototype.keys()` returns an iterator over numbers. * `Array.prototype.values()` returns an iterator. * `Array.prototype.entries()` returns an iterator over key-value pairs. The keys are numbers. * Sets: * `Set.prototype.values()` returns an iterator. * `Set.prototype.keys()` returns an iterator. Equivalent to `.values()`. * `Set.prototype.entries()` returns an iterator over value-value pairs (i.e., both components of the pair are the same value). * Maps: * `Map.prototype.keys()` returns an iterator. * `Map.prototype.values()` returns an iterator. * `Map.prototype.entries()` returns an iterator over key-value pairs. The following methods return iterators: * `String.prototype.matchAll()` returns an iterator over match objects. ##### Other sources of iterators Generators also return iterators: ```js function* gen() {} assert.equal( gen() instanceof Iterator, true ); ```