Sub topic 13
Using the Counter Argument in Callbacks
This chapter assumes you already know how map and filter work on iterators and how to chain them into a pipeline. It also assumes you have used the index argument of Array.prototype.map. Iterator helpers have a similar argument, but it is called a counter, and it behaves differently in a few ways that matter.
What the counter is
Every iterator helper that takes a callback passes it two arguments:
value: the current value pulled from the underlying iterator.counter: a whole number that starts at0and goes up by one for each value this helper has received.
const labels = ['a', 'b', 'c']
.values()
.map((value, index) => `${index}:${value}`)
.toArray();
console.log(labels); // ['0:a', '1:b', '2:c']The .values() call matters here. Arrays do not inherit from Iterator.prototype, so you need an array iterator before you can call the helper map. If you called map directly on the array, you would get Array.prototype.map, which is eager and returns an array.
The specification calls this argument a counter, not an index. An iterator has no positions you can jump back to. The counter only records how many values have passed through one stage so far.
Which methods pass a counter
| Method | Callback signature | Counter starts at |
|---|---|---|
| `map` | `(value, counter)` | 0 |
| `filter` | `(value, counter)` | 0 |
| `flatMap` | `(value, counter)` | 0 |
| `forEach` | `(value, counter)` | 0 |
| `some` | `(value, counter)` | 0 |
| `every` | `(value, counter)` | 0 |
| `find` | `(value, counter)` | 0 |
| `reduce` | `(accumulator, value, counter)` | 0 with an initial value, 1 without |
| `take`, `drop` | no callback | not applicable |
take and drop take a number, not a function, so they have no counter. They do still change the counters that later stages see, as the next sections show.
There is no third argument
Array.prototype.map passes (element, index, array). Iterator helpers pass only two arguments. No collection exists to hand over, because the source might be a generator, a network stream, or an infinite sequence.
const result = [5, 6].values().map((value, counter, third) => {
return [value, counter, third];
}).toArray();
console.log(result); // [[5, 0, undefined], [6, 1, undefined]]Code ported from arrays that reads arr[i + 1] or arr.length inside the callback will fail silently: third is undefined, so third.length throws a TypeError and third?.length gives undefined. If you need neighbouring values, write a small generator that yields pairs or windows, then run helpers over that.
Each stage has its own counter
This is the behaviour most likely to surprise you. A pipeline does not share one counter. Each helper counts the values that reach it.
const out = [10, 11, 12, 13, 14, 15]
.values()
.filter((value, i) => {
console.log('filter sees', i, value);
return value % 2 === 0;
})
.map((value, i) => `${i}:${value}`)
.toArray();
console.log(out); // ['0:10', '1:12', '2:14']filter sees counters 0 through 5, because it receives all six values. map sees only the three values that filter let through, so its counter runs 0, 1, 2. The map counter says "third value I received", not "position in the original array".
drop has the same effect even though it has no callback:
const afterDrop = [10, 20, 30, 40].values()
.drop(2)
.map((value, i) => [i, value])
.toArray();
console.log(afterDrop); // [[0, 30], [1, 40]]The counter in map starts at 0 for the value 30, because map never received 10 or 20.
Keeping the original position
If you need the original position later in the pipeline, record it as data at the start, before any filter or drop:
const words = ['alpha', 'be', 'gamma', 'do', 'epsilon'];
const longWords = words.values()
.map((word, position) => ({ word, position }))
.filter(({ word }) => word.length > 2)
.map(({ word, position }) => `${position}:${word}`)
.toArray();
console.log(longWords); // ['0:alpha', '2:gamma', '4:epsilon']For arrays there is a built-in shortcut. Array.prototype.entries() returns an iterator of [index, value] pairs, and that iterator inherits from Iterator.prototype:
const evensWithIndex = [7, 8, 9, 10].entries()
.filter(([, value]) => value % 2 === 0)
.toArray();
console.log(evensWithIndex); // [[1, 8], [3, 10]]Map.prototype.entries() returns [key, value] pairs, which is not the same thing. For Maps and other non-array sources, use the first map approach.
The counter in consuming methods
Consuming methods count the values they pull from the end of the pipeline. find with a counter is a quick way to stop at a known count:
function* naturals() {
let n = 0;
while (true) yield n++;
}
const found = naturals()
.filter((n) => n % 7 === 0)
.find((n, i) => i === 3);
console.log(found); // 21find sees 0, 7, 14, 21 with counters 0, 1, 2, 3, and returns 21. The infinite generator stops there, because find closes the iterator once it has an answer. Code that is easier to read would use .drop(3).take(1), but this example shows how the counter lines up with the filtered output.
reduce needs care. With an initial value, the first callback gets counter 0. Without one, the first value becomes the accumulator and is not passed to the callback, so the first callback call receives the second value with counter 1:
const withInit = [10, 20, 30].values()
.reduce((acc, value, i) => { console.log('with init', i); return acc + value; }, 0);
// with init 0
// with init 1
// with init 2
const withoutInit = [10, 20, 30].values()
.reduce((acc, value, i) => { console.log('without init', i); return acc + value; });
// without init 1
// without init 2
console.log(withInit, withoutInit); // 60 60Array.prototype.reduce behaves the same way, so this rule should look familiar.
Passing existing functions as callbacks
Passing a built-in function straight to map hits the same trap as it does with arrays: the counter becomes the function's second argument.
const parsed = ['10', '10', '10'].values().map(parseInt).toArray();
console.log(parsed); // [10, NaN, 2]parseInt('10', 0) treats radix 0 as base 10. parseInt('10', 1) is NaN, because 1 is not a valid radix. parseInt('10', 2) reads the string as binary and gives 2. Wrap the function so it receives only the value:
const fixed = ['10', '10', '10'].values().map((s) => parseInt(s, 10)).toArray();
console.log(fixed); // [10, 10, 10]Counter and laziness
The counter goes up only when a value is pulled. A helper that is created but never consumed never calls its callback, so its counter never advances. If you pull only two values from a pipeline, map sees counters 0 and 1 and nothing more. This makes the counter a cheap way to log how far a lazy pipeline actually ran while you debug it.
Exercise
What does this print? console.log(['a','b','c','d','e'].values().drop(1).filter((v, i) => i % 2 === 0).map((v, i) => v + i).toArray());
Show answer
['b0', 'd1']. After drop(1), filter receives b, c, d, e with counters 0, 1, 2, 3 and keeps the values at counters 0 and 2, which are b and d. Then map receives b and d with counters 0 and 1.
Exercise
A colleague writes scores.values().filter((s) => s > 50).map((s, i) => ({ s, originalIndex: i })). Why is originalIndex wrong, and how do you fix it?
Show answer
The map counter counts only the values that passed the filter, not their positions in scores. Record the position before filtering, either with scores.values().map((s, i) => ({ s, originalIndex: i })).filter(({ s }) => s > 50) or with scores.entries().filter(([, s]) => s > 50).
Exercise
In [1, 2, 3, 4].values().reduce((acc, v, i) => acc + v * i), which counters does the callback receive, and what is the result?
Show answer
There is no initial value, so 1 becomes the accumulator. The callback receives counters 1, 2, and 3 for the values 2, 3, and 4. The result is 1 + 2·1 + 3·2 + 4·3 = 21.