Sub topic 5
Selecting Values with filter
This chapter assumes you know generator functions, the next() protocol, and the lazy behavior of map covered in earlier chapters. Iterator.prototype.filter keeps only the values for which a predicate returns a truthy result. Like map, it returns a new iterator helper and does no work until you pull from it.
The Basic Shape
filter(predicate) calls predicate(value, counter) for each value it pulls from the source. If the result is truthy, the value is passed through. If it is falsy, the value is discarded and filter pulls the next one.
function* naturals() {
let n = 0;
while (true) yield n++;
}
const multiplesOf3 = naturals().filter((n) => n % 3 === 0);
console.log(multiplesOf3.next().value); // 0
console.log(multiplesOf3.next().value); // 3
console.log(multiplesOf3.next().value); // 6The source is infinite, and that causes no problem. Each next() call reads only as many naturals as it needs to find one match.
How One next() Call Works
map reads exactly one source value per next() call. filter can read several. It keeps pulling until a value passes or the source is exhausted.
You can watch this happen by logging inside the predicate:
const it = [5, 8, 1, 12].values().filter((n) => {
console.log('testing', n);
return n > 6;
});
console.log(it.next());
// testing 5
// testing 8
// { value: 8, done: false }
console.log(it.next());
// testing 1
// testing 12
// { value: 12, done: false }
console.log(it.next());
// { value: undefined, done: true }Truthy, Not true
The predicate's result is coerced to a boolean, so passing Boolean itself as the predicate is a common way to remove falsy values:
const cleaned = ['a', '', null, 'b', 0, 'c'].values().filter(Boolean).toArray();
console.log(cleaned); // ['a', 'b', 'c']Coercion can also hide bugs. (n) => n % 2 keeps odd numbers, because 1 is truthy. You may have meant to keep even numbers.
Common Errors
| Mistake | Symptom | Fix |
|---|---|---|
| Predicate that never matches on an infinite source | `next()` never returns | Bound the source with `take` first, or make sure a match is guaranteed |
| Passing a non-function | `TypeError` thrown when `filter` is called | Pass a callable predicate |
| Relying on truthiness by accident | Wrong values kept | Return an explicit comparison |
The non-function check happens immediately, before any value is pulled:
try {
[1, 2, 3].values().filter('not a function');
} catch (e) {
console.log(e instanceof TypeError); // true
}Exercise
Given const it = [2, 3, 4, 7, 9].values().filter((n) => n > 5), how many times does the predicate run during the first it.next() call, and what value is returned?
Show answer
The predicate runs four times, testing 2, 3, 4, and 7. It stops at 7, the first value that passes, and the call returns { value: 7, done: false }. The value 9 has not been read yet.
Exercise
Why does naturals().filter((n) => n < 0).next() never finish, while naturals().take(10).filter((n) => n < 0).next() returns right away?
Show answer
In the first case, filter keeps pulling from an infinite source looking for a match that never comes. In the second case, take(10) ends the source after ten values, so filter sees done and returns { value: undefined, done: true }.