Sub topic 5
Selecting Values with filter
This chapter assumes you know generator functions, the iterator protocol (next() returning { value, done }), and how Array.prototype.filter behaves. It also builds on the idea from earlier chapters that iterator helpers are lazy: they do no work until something pulls a value.
Iterator.prototype.filter(predicate) returns a new iterator. That iterator yields only the values from the source for which predicate returns a truthy result. The idea matches the array version. The way it does the work is different, and the differences matter once your source is large, infinite, or has side effects.
The basic shape
function* readings() {
yield 12;
yield -3;
yield 40;
yield 0;
yield 7;
}
const positive = readings().filter((n) => n > 0);
console.log(positive.next()); // { value: 12, done: false }
console.log([...positive]); // [40, 7]positive is an iterator helper object. It has next() and return(), and it inherits from Iterator.prototype, so you can chain more helpers onto it. Calling filter does not run the predicate even once. The first next() call starts the work.
How one next() call works
map pulls exactly one source value for each next() call. filter is different, because a single next() call on a filter helper may pull many values from the source. The helper keeps pulling until it finds a value that passes the predicate or the source runs out.
You can watch this loop by logging on both sides:
function* source() {
for (const n of [1, 2, 3, 4, 5, 6]) {
console.log('yield', n);
yield n;
}
}
const multiplesOfThree = source().filter((n) => {
console.log('test', n);
return n % 3 === 0;
});
console.log(multiplesOfThree.next());
// yield 1
// test 1
// yield 2
// test 2
// yield 3
// test 3
// { value: 3, done: false }The output interleaves. Each value is yielded and tested before the next one is produced. The helper never builds a batch of values and then tests the batch. Values 4, 5, and 6 are never produced, because nobody asked for a second result.
Truthiness, not true
The helper checks the predicate's return value for truthiness, exactly as Array.prototype.filter does. Any truthy value keeps the element and any falsy value drops it. Passing Boolean as the predicate is a short way to remove empty strings, 0, null, undefined, NaN, and false:
const raw = ['alpha', '', null, 'beta', 0, undefined, 'gamma'];
const cleaned = raw.values().filter(Boolean).toArray();
console.log(cleaned); // ['alpha', 'beta', 'gamma']This is also a common source of bugs. A predicate that returns a number, such as (item) => item.count, drops every item whose count is 0. Write the comparison you mean, such as item.count !== undefined.
The counter argument
The predicate receives two arguments, the value and a counter. The counter is a zero-based count of how many values the helper has pulled from the source. It counts rejected values too, so it matches the value's position in the source and not its position in the output.
const picked = ['a', 'b', 'c', 'd', 'e']
.values()
.filter((value, index) => index % 2 === 0)
.toArray();
console.log(picked); // ['a', 'c', 'e']Unlike the array version, there is no third argument. The array version passes the whole array as the third argument, but an iterator has no collection to pass. A later chapter covers the counter in more depth.
Filtering infinite sequences
Because filter pulls on demand, it works on endless sources. You only need something downstream that stops pulling:
function* naturals() {
let n = 1;
while (true) yield n++;
}
const firstFiveSquares = naturals()
.filter((n) => Number.isInteger(Math.sqrt(n)))
.take(5)
.toArray();
console.log(firstFiveSquares); // [1, 4, 9, 16, 25]There is a gotcha here that take does not solve. take(5) limits how many values come out, but each of those values still has to be found by filter. If the predicate never matches, or matches fewer than five times, the filter helper keeps pulling forever and the program hangs:
// Do not run: this never finishes.
// naturals().filter((n) => n < 0).take(1).toArray();The order of the two calls changes the meaning:
| Pipeline | What it means | Ends on an infinite source? |
|---|---|---|
| `.filter(p).take(n)` | The first `n` values that match | Only if at least `n` values match |
| `.take(n).filter(p)` | The matches among the first `n` values | Always |
Order relative to map
When you combine filter with map, putting filter first usually saves work. map then runs only on values you keep. Put map first only when the predicate needs the transformed value:
const users = [
{ name: 'Ada', active: true },
{ name: 'Bo', active: false },
{ name: 'Cy', active: true },
];
const activeNames = users
.values()
.filter((u) => u.active)
.map((u) => u.name.toUpperCase())
.toArray();
console.log(activeNames); // ['ADA', 'CY']Errors and cleanup
If you pass something that is not a function, filter throws a TypeError as soon as you call it. You do not have to wait for the first next():
try {
[1, 2, 3].values().filter('not a function');
} catch (e) {
console.log(e instanceof TypeError); // true
}If the predicate throws while the helper is running, the helper first closes the source by calling its return() method, and then it rethrows the error. For a generator source, closing means its finally blocks run:
function* source() {
try {
yield 1;
yield 2;
yield 3;
} finally {
console.log('source closed');
}
}
const checked = source().filter((n) => {
if (n === 2) throw new Error('bad value');
return true;
});
console.log(checked.next().value); // 1
try {
checked.next();
} catch (e) {
console.log(e.message);
}
// source closed
// bad valueAfter that, the helper is finished, and calling checked.next() again returns { value: undefined, done: true }. If you call return() on a filter helper yourself, it forwards the call to the source in the same way. This is how take and break in a for...of loop release resources further up a pipeline.
Array filter versus iterator filter
| Aspect | `Array.prototype.filter` | `Iterator.prototype.filter` |
|---|---|---|
| When the predicate runs | All at once, during the call | One value at a time, as values are pulled |
| Result | A new array | An iterator, which can be used only once |
| Predicate arguments | `(value, index, array)` | `(value, counter)` |
| Infinite sources | Not possible | Supported, if something stops pulling |
| Memory | Holds every kept element | Holds one value at a time |
| Bad predicate argument | `TypeError` when called | `TypeError` when called |
Exercise
Given function* g() { yield 'x'; yield ''; yield 'y'; } and const it = g().filter((s, i) => { console.log(i); return s; });, what is logged by console.log(it.next().value); console.log(it.next().value);?
Show answer
It logs 0, then x, then 1, 2, and y. The first next() tests 'x' with counter 0, which passes. The second next() tests '' with counter 1, which is falsy and rejected, then tests 'y' with counter 2, which passes. So one next() call ran the predicate twice.
Exercise
You need the first 3 even numbers in an infinite generator that yields only odd numbers. Will odds().filter((n) => n % 2 === 0).take(3).toArray() return an empty array? If not, how would you bound the work?
Show answer
It does not return. filter keeps pulling forever looking for an even number, so the program hangs. To bound the work, limit the source before filtering, for example odds().take(10000).filter((n) => n % 2 === 0).take(3).toArray(), which returns [] after testing at most 10000 values.
Exercise
Why does the predicate-throwing example print "source closed" before "bad value"?
Show answer
When the predicate throws, the filter helper calls return() on the source generator before it rethrows the error. Calling return() runs the generator's finally block, which logs "source closed". After that, the error reaches the catch block, which logs "bad value".