Terminology (4)Terms used in this lesson
Term on the front, definition on the back. Paste with tabs between fields and a new line between cards, or import the download in Anki as Basic.
- Cursor
- Retained traversal state describing which item can be requested next.
- Lazy operation
- Work deferred until the consumer requests an item.
- Lookahead
- An already observed item retained for a later logical request.
- Exhaustion
- The source has no next item, distinct from a valid zero payload.
State, demand, and deferred work
An iterator represents progress through a source. A request advances that progress or reports completion; a yielded value is distinct from the completion signal. A generator or producer defines how values become available, but restarting a producer and resuming an existing cursor need not mean the same thing.
Lazy work is deferred until a consumer requests it. To reason about that work, name what you count: source values obtained, transformations performed or results retained. Incremental processing also needs enough state to continue from the same boundary on the next request.
01Native iteration
Find the position held between reading requests
A sensor dashboard asks for a short preview instead of the entire reading log. Each request should authorize only the source work it needs. Preparing readings for display adds another cost, and summarizing equal readings in successive groups requires the requests to share a position in that stream.
The first reading is zero. Distinguish it from completion, then trace the selected program’s traversal operations and any copied cursor state.
function* readings(): IterableIterator<number> {
for (const value of [0, 4, 4]) {
console.log("visit", value);
yield value;
}
}
const cursor = readings();
console.log(cursor.next().value);
console.log(cursor.next().value);
npx tsc main.ts --noEmit --skipLibCheck --target es2022 --module nodenext --types node && node main.ts
Save one complete example at a time in a fresh folder under the selected filename. Run the shown checking/build command before execution. The browser lab supplies its editor, stdin fixtures and native runner.
02Bounded demand
Measure the work behind a one-reading preview
The preview now retains one value and stops. Predict whether its raw-demand counter also stops at one.
let pulls = 0;
function* raw(): IterableIterator<number> {
for (const value of [2, 5, 8]) {
pulls += 1;
yield value;
}
}
const out: number[] = [];
for (const value of raw()) {
if (out.length === 1) break;
out.push(value);
}
console.log(out.length, pulls);
03Lazy work
Prepare a reading only when the display asks
Each valid reading needs a display preparation, represented here by doubling it and counting that work. Predict the counter before consumption and after one requested result.
let work = 0;
function* prepared(): IterableIterator<number> {
for (const value of [3, 7]) {
work += 1;
yield value * 2;
}
}
const cursor = prepared();
console.log("before", work);
console.log(cursor.next().value, work);
04Retained state
Keep track of the reading that reveals a boundary
The dashboard next summarizes consecutive equal readings. Before building that report, inspect a cursor that stops when it encounters the first different value. Which item has it already observed, and what remains available?
const cursor = [2, 2, 5, 5].values();
const first = cursor.next().value;
let pending: number | null = null;
for (const value of cursor) {
if (value !== first) {
pending = value;
break;
}
}
console.log("boundary", pending);
console.log("resume", cursor.next().done);
05Practice
Repair the incremental reading pipeline
Continue the dashboard’s previews and consecutive-run summary. Input is prefix limit, group-request count, reading count, then signed readings. The complete source adapters, counters and caller are supplied. Accepted nonnegative readings are prepared by doubling; negative readings are discarded.
Every report starts a fresh raw source. pulls counts values returned by the supplied raw adapter; prepared counts actual prepare calls. It does not count OS reads. A prepared prefix permits only the raw visits needed to supply that prefix or discover exhaustion.
Each group is one maximal consecutive run in the prepared stream. Repeated requests share state and allow at most the one prepared boundary needed to close a requested group. Return the final run at exhaustion, and report end on later requests.
The supplied finite inputs are well formed; limits, request counts and lengths are nonnegative. Readings, doubling and counters fit the shown native types. These are input assumptions, not a reader-validation assignment.
Start the lab
Bound a raw prefix, retain lazy preparation, then preserve group boundaries across calls.
In the frontend A render can display cursor results; advancing the cursor belongs to an explicit event. Optional
A Next reading button should retain one cursor between clicks. Creating a fresh cursor in every click restarts the sequence, while advancing during rendering ties consumption to rendering rather than user demand.
'use client';
import { useRef, useState } from 'react';
export function NextReading() {
const cursor = useRef([0, 4, 4].values());
const [label, setLabel] = useState('Ready');
function advance() {
const item = cursor.current.next();
setLabel(item.done ? 'End' : String(item.value));
}
return <button onClick={advance}>{label}</button>;
}
The ref retains the iterator object across renders. Its next call happens only in the event handler; setting label publishes the result. The done flag preserves zero as a valid reading.
Sources: React: useRef and event handlers,Svelte: event handlers.
Sign in to keep your read marks on every device. Sign in
Was this helpful?