Sub topic 8
Getting Results Out: toArray, reduce, and Friends
This chapter assumes you know generator functions, for...of, and the lazy helpers map, filter, take, and drop. Those helpers return new iterators and do no work on their own. The methods covered here are different: they pull values through the pipeline and give you a final result.
The Consuming Methods
Every iterator that inherits from Iterator.prototype has six methods that consume it:
| Method | Returns | Stops early? |
|---|---|---|
| `toArray()` | An array of every value | No |
| `reduce(fn, initial)` | A single accumulated value | No |
| `forEach(fn)` | `undefined` | No |
| `some(fn)` | `true` once `fn` returns truthy, otherwise `false` | Yes, on the first truthy result |
| `every(fn)` | `false` once `fn` returns falsy, otherwise `true` | Yes, on the first falsy result |
| `find(fn)` | The first matching value, or `undefined` | Yes, on the first match |
Each callback receives the value and a zero-based counter. The reduce callback receives the accumulator first.
function* nums() {
yield 3;
yield 8;
yield 5;
yield 12;
}
console.log(nums().toArray()); // [3, 8, 5, 12]
console.log(nums().reduce((sum, n) => sum + n, 0)); // 28
nums().forEach((n, i) => console.log(i, n)); // 0 3, 1 8, 2 5, 3 12
console.log(nums().some((n) => n > 10)); // true
console.log(nums().every((n) => n > 2)); // true
console.log(nums().find((n) => n % 2 === 0)); // 8Each line calls nums() again because a consumed iterator cannot be read a second time.
Short-Circuiting
some, every, and find stop pulling values as soon as they know the answer. Then they close the underlying iterator. A logging generator shows how many values were actually produced:
function* logged() {
for (const n of [1, 2, 3, 4]) {
console.log('yield', n);
yield n;
}
}
console.log(logged().find((n) => n === 2));
// yield 1
// yield 2
// 2Values 3 and 4 are never produced. Because of this, find, some, and every are safe on infinite sequences as long as an answer eventually turns up. toArray, reduce, and forEach read until the iterator is done, so on an infinite source they never return unless you put a take in front of them.
Common Errors
try {
[].values().reduce((a, b) => a + b);
} catch (e) {
console.log(e instanceof TypeError); // true
}
console.log([].values().reduce((a, b) => a + b, 0)); // 0Other mistakes to watch for:
- Expecting
forEachto return something useful. It returnsundefined, so use it only for side effects. - Treating a
findresult ofundefinedas "not found" when the sequence itself can containundefined. Usesomeif you only need to know whether a match exists. - Using
toArray()and then checking a condition on the array. That reads every value even whensomeorfindcould have stopped early.
Exercise
Using the logged() generator from this chapter, what does console.log(logged().every((n) => n < 2)) print, and why?
Show answer
It prints "yield 1", "yield 2", then false. The value 1 passes the test. The value 2 fails it, so every returns false right away and closes the generator. Values 3 and 4 are never produced.
Exercise
You need the sum of the first 100 squares from an infinite naturals() generator. Which consuming method do you use, and what must come before it?
Show answer
Use reduce with an initial value of 0, preceded by take(100): naturals().map((n) => n * n).take(100).reduce((s, n) => s + n, 0). Without take, reduce would never finish.