Sub topic 14
Wrapping Any Iterator with Iterator.from
This chapter assumes you know the iteration protocol, that generators and built-in iterators inherit from Iterator.prototype, and how map, filter, take, and drop behave. Earlier chapters showed that the helpers are available only on objects whose prototype chain includes Iterator.prototype. Plenty of iterators in real code don't meet that condition. Hand-written iterators, objects returned by older libraries, and iterators built from plain object literals all lack the helpers. Iterator.from connects those objects to the helper methods.
The Problem: Iterators Without the Prototype
An object counts as an iterator under the protocol if it has a working next() method. The protocol does not require any particular prototype, so the following object is a valid iterator. It still has no map method:
const iteratorLike = {
i: 0,
next() {
return this.i < 3
? { value: this.i++, done: false }
: { value: undefined, done: true };
},
};
console.log(typeof iteratorLike.map); // undefinedYou could still loop over it by calling next() by hand. You could not pass it to for...of, because it has no Symbol.iterator method. You also could not chain helpers on it. Iterator.from fixes both problems:
const iteratorLike = {
i: 0,
next() {
return this.i < 3
? { value: this.i++, done: false }
: { value: undefined, done: true };
},
};
const out = Iterator.from(iteratorLike).map((x) => x + 1).toArray();
console.log(out); // [1, 2, 3]What Iterator.from Accepts
Iterator.from is a static method on the global Iterator constructor. It takes one argument and accepts two shapes of input:
| Input | Example | What happens |
|---|---|---|
| An iterable (has a `Symbol.iterator` method) | arrays, `Set`, `Map`, generator objects, custom iterables | Calls `Symbol.iterator` and uses the iterator it returns |
| An iterator-like object (no `Symbol.iterator`) | `{ next() { ... } }` | Treats the object itself as the iterator |
| A primitive string | `'abc'` | Iterates the string's code points |
| Any other primitive | `42`, `null`, `undefined`, `true` | Throws a `TypeError` |
Strings are the only primitive it allows. They iterate by code point, which matches for...of over a string:
console.log(Iterator.from('a😀b').toArray()); // ['a', '😀', 'b']
try {
Iterator.from(42);
} catch (e) {
console.log(e instanceof TypeError); // true
}How It Works Internally
After Iterator.from has an iterator in hand, it checks whether that iterator already inherits from Iterator.prototype. The answer decides what it returns.
Already a proper iterator: returned as-is
Generator objects and built-in iterators already inherit from Iterator.prototype. For these, Iterator.from returns the exact same object and creates no wrapper:
function* gen() {
yield 1;
yield 2;
}
const g = gen();
console.log(Iterator.from(g) === g); // true
const arrayIter = Iterator.from([10, 20, 30]);
console.log(arrayIter.drop(1).toArray()); // [20, 30]When you pass an array, Iterator.from calls array[Symbol.iterator](). That call returns the same kind of array iterator you would get from .values(), and that iterator already has the helpers.
Not a proper iterator: wrapped
In every other case, Iterator.from returns a new wrapper object. The wrapper inherits from Iterator.prototype, so it has all the helpers. It also has two methods of its own:
next()calls the underlying iterator'snextwiththisset to the underlying object, and passes the result through unchanged.return()calls the underlyingreturn()if one exists. If none exists, it returns{ value: undefined, done: true }.
The wrapper has no throw() method. The helpers never use throw(), so this rarely matters.
This case covers iterables whose Symbol.iterator returns a bare iterator, which is a common pattern in older code:
const legacyRange = {
[Symbol.iterator]() {
let n = 0;
return {
next: () =>
n < 3 ? { value: n++, done: false } : { value: undefined, done: true },
};
},
};
console.log(typeof legacyRange[Symbol.iterator]().map); // undefined
console.log(Iterator.from(legacyRange).map((x) => x * 10).toArray()); // [0, 10, 20]Cleanup Passes Through the Wrapper
The wrapper forwards return(), so early termination still reaches your iterator. When take reaches its limit, it closes the iterator it reads from. Here that iterator is the wrapper, and the wrapper calls your return():
const raw = {
i: 0,
next() {
return { value: this.i++, done: false };
},
return() {
console.log('raw closed');
return { value: undefined, done: true };
},
};
const firstTwo = Iterator.from(raw).take(2).toArray();
console.log(firstTwo);
// raw closed
// [0, 1]If your iterator holds a resource such as a file handle, a database cursor, or a subscription, add a return() method and you get cleanup through any helper chain for free.
Gotchas
The next method is read once
The wrapper reads the next property once, when you call Iterator.from, and stores it. If you replace obj.next afterwards, the wrapper keeps calling the original function:
const obj = {
next() {
return { value: 'original', done: false };
},
};
const wrapped = Iterator.from(obj);
obj.next = () => ({ value: 'replaced', done: false });
console.log(wrapped.next().value); // originalThe wrapper shares state with the original
Wrapping copies nothing. Both the wrapper and the original object drive the same underlying iterator, so pulling from one advances the other. Pick one handle and use only that one.
const source = [1, 2, 3, 4][Symbol.iterator]();
const sameObject = Iterator.from(source); // returned as-is, same object
source.next(); // consumes 1
console.log(sameObject.toArray()); // [2, 3, 4]Iterator.from is not Array.from
The names look alike, but the two methods behave in opposite ways. Array.from reads the whole source right away and builds an array. Iterator.from reads nothing up front and gives you back a lazy iterator. If the source is infinite, Array.from never finishes. Iterator.from(source).take(5) is fine.
Alternatives to wrapping
If you write the iterator yourself, you can skip the wrapper altogether. Either write a generator function, or extend the abstract Iterator class so that instances inherit the helpers directly:
class Countdown extends Iterator {
#n;
constructor(start) {
super();
this.#n = start;
}
next() {
return this.#n > 0
? { value: this.#n--, done: false }
: { value: undefined, done: true };
}
}
console.log(new Countdown(3).map((x) => x * 2).toArray()); // [6, 4, 2]Calling new Iterator() directly throws a TypeError, because Iterator is meant to be used only as a base class. Subclassing it works. Use Iterator.from for iterators you don't control. Use generators or subclasses for iterators you write.
Common Errors
| Symptom | Cause | Fix |
|---|---|---|
| `TypeError: x.map is not a function` on a custom iterator | The iterator doesn't inherit from `Iterator.prototype` | Wrap it: `Iterator.from(x).map(...)` |
| `TypeError` from `Iterator.from(value)` | `value` is a number, boolean, `null`, or `undefined` | Pass an object or a string |
| The pipeline skips the first few values | Something else already called `next()` on the same iterator | Create a fresh iterator for each pipeline |
| Cleanup never runs | The underlying iterator has no `return()` method | Add `return()`, or use a generator with `finally` |
Exercise
Given function* g() { yield 1; } and const it = g();, what does Iterator.from(it) === it print, and why? What changes if it is instead the object { next() { return { value: 1, done: false }; } }?
Show answer
It prints true. Generator objects already inherit from Iterator.prototype, so Iterator.from returns them unchanged. The plain object does not inherit from Iterator.prototype, so Iterator.from returns a new wrapper object, and the comparison prints false.
Exercise
A library returns cursor, an object with next() and return() methods but no Symbol.iterator. Write one expression that gets the first 10 values whose active property is true, and explain whether cursor.return() gets called.
Show answer
Iterator.from(cursor).filter((row) => row.active).take(10).toArray(). If 10 matching rows are found before the cursor runs out, take closes its source when it hits the limit. That close travels through filter to the Iterator.from wrapper, which calls cursor.return(). If the cursor runs out first, it is exhausted normally and return() is not called.
Exercise
Why does Iterator.from({ [Symbol.iterator]: () => [1, 2][Symbol.iterator]() }) return an object with helpers, and is that object a wrapper?
Show answer
Iterator.from calls the Symbol.iterator method, which returns an array iterator. Array iterators already inherit from Iterator.prototype, so Iterator.from returns that array iterator directly with no wrapper.