Sub topic 4
Transforming Values with map
This chapter assumes you know generator functions, for...of, spread syntax, and Array.prototype.map. It also builds on the earlier chapters on Iterator.prototype and lazy evaluation.
What map does
Iterator.prototype.map(mapper) returns a new iterator. Each time you call next() on that iterator, it pulls one value from the source, passes the value to mapper, and yields whatever mapper returns. The source is not changed, and no array is built along the way.
function* readings() {
yield 20;
yield 25;
yield 30;
}
const fahrenheit = readings().map((c) => (c * 9) / 5 + 32);
console.log(fahrenheit.next()); // { value: 68, done: false }
console.log([...fahrenheit]); // [77, 86]The first next() call converts only 20. The spread then drains the remaining two values. When the source reports done: true, the mapped iterator reports done: true as well.
Works on any built-in iterator
Every built-in iterator inherits from Iterator.prototype. That includes generators, Map and Set iterators, string iterators, and array iterators, so map is available on all of them. Map entries are a common case:
const prices = new Map([
['apple', 1.2],
['pear', 0.8],
]);
const lines = prices
.entries()
.map(([name, price]) => `${name}: $${price.toFixed(2)}`);
for (const line of lines) console.log(line);
// apple: $1.20
// pear: $0.80The mapper receives each [key, value] entry, so destructuring works the same way it does in a for...of loop.
How it compares to Array map
| Aspect | `Array.prototype.map` | `Iterator.prototype.map` |
|---|---|---|
| Returns | A new array | A new iterator |
| When the mapper runs | Immediately, for every element | Once per `next()` call |
| Memory | Holds all results | Holds one value at a time |
| Can be reused | Yes | No, it is consumed once |
Common errors
- Expecting an array.
console.log(readings().map(f))prints an iterator object, not values. Call.toArray()or spread the iterator when you need an array. - Calling map on an array and expecting laziness.
[1, 2, 3].map(f)is the eager array method. Use[1, 2, 3].values().map(f)to get the lazy version. - Async mappers.
mapdoes not await anything. Anasyncmapper yields promises, so you get an iterator of promises, not resolved values. - Passing a non-function.
readings().map(42)throws aTypeErrorimmediately, before any value is pulled.
The mapper also receives a second argument, a zero-based counter. A later chapter covers it.
Exercise
What does this code print? const it = new Set(['a', 'b', 'c']).values().map((s) => s.toUpperCase()); it.next(); console.log([...it]);
Show answer
It prints ['B', 'C']. The first next() call pulls and maps 'a', and that result is discarded. The spread then consumes only the remaining two values.
Exercise
Rewrite const squares = [1, 2, 3, 4].map((n) => n * n); so that it produces a lazy iterator instead of an array.
Show answer
const squares = [1, 2, 3, 4].values().map((n) => n * n); Calling .values() returns an array iterator, which inherits the iterator helper map from Iterator.prototype.