Skip to content

Iterators and generators

Relay’s upstream API lists jobs one page at a time, with a cursor to ask for the next page. The simple way to read them all is a loop that collects every page into one array. That fetches thousands of jobs when the caller wanted the first ten.

A generator produces values on demand. This lesson shows the types behind iteration, then builds helpers that work on any sequence and a paginator that fetches the next page only when someone asks for an item from it.

for...of and spread ([...xs]) work on anything that is Iterable<T>: an object with a [Symbol.iterator]() method that returns an Iterator<T>. Arrays, strings, Set and Map all qualify.

function count(xs: Iterable<unknown>): number {
let n = 0
for (const _ of xs) n++
return n
}
count([1, 2, 3])
count(new Set(["a", "b"]))
count("hello")
// @ts-expect-error: a number is not iterable
count(5)

Taking Iterable<T> instead of T[] makes a function work for all of them.

A function written with function* returns a generator. yield hands out one value and pauses until the caller asks for the next one:

function* ids(prefix: string): Generator<string, void, unknown> {
for (let n = 1; ; n++) yield `${prefix}-${n}`
}
const gen = ids("job")
gen.next() // { value: "job-1", done: false }
gen.next() // { value: "job-2", done: false }

The loop never ends, and that is fine: nothing runs until next() is called. The type Generator<T, TReturn, TNext> has three parameters. T is what yield produces. TReturn is what the function returns at the end, and TNext is what the caller can pass into next(value). Most code only cares about T, so void and unknown are the usual other two.

Because ids is infinite, you need a way to stop. take is a generic helper over any iterable:

function* take<T>(xs: Iterable<T>, n: number): Generator<T, void, unknown> {
if (n <= 0) return
let seen = 0
for (const x of xs) {
yield x
if (++seen >= n) return
}
}
function* ids(): Generator<string, void, unknown> {
for (let n = 1; ; n++) yield `job-${n}`
}
const firstThree = [...take(ids(), 3)] // string[]: ["job-1", "job-2", "job-3"]

take returns as soon as it has n items, and for...of closes the source. A version that built an array first, like [...xs].slice(0, n), would never finish on an infinite source. Laziness is a property of the code, not of the type, so tests check it by recording what was read.

The same shape works for grouping. Relay posts jobs to a bulk endpoint that accepts 50 at a time:

function* chunk<T>(xs: Iterable<T>, size: number): Generator<T[], void, unknown> {
if (size < 1) throw new Error("chunk size must be at least 1")
let current: T[] = []
for (const x of xs) {
current.push(x)
if (current.length === size) {
yield current
current = []
}
}
if (current.length > 0) yield current
}
const groups = [...chunk([1, 2, 3, 4, 5], 2)] // number[][]: [[1, 2], [3, 4], [5]]

T is inferred from the input, and the output is Generator<T[]>. The last chunk may be shorter. Note that the size check runs on the first next(), not when chunk is called, because a generator body does not start until then.

An AsyncIterable<T> produces values that arrive later. You write one with async function* and read it with for await:

async function* countdown(from: number): AsyncGenerator<number, void, unknown> {
for (let n = from; n > 0; n--) {
await Promise.resolve() // pretend this is a network call
yield n
}
}
async function main() {
for await (const n of countdown(3)) {
n // number
}
}

for await works on an AsyncIterable and, as a convenience, on a plain Iterable. The loop asks for one value, waits, runs the body, then asks for the next.

Now the real case. fetchPage takes a cursor and returns a page of items plus the next cursor, or null at the end. paginate turns that into a flat, lazy stream of items:

interface Page<T> {
readonly items: readonly T[]
readonly next: string | null
}
async function* paginate<T>(
fetchPage: (cursor: string | null) => Promise<Page<T>>,
): AsyncGenerator<T, void, unknown> {
let cursor: string | null = null
do {
const page: Page<T> = await fetchPage(cursor)
yield* page.items
cursor = page.next
} while (cursor !== null)
}
interface Job {
readonly id: string
}
declare function fetchJobs(cursor: string | null): Promise<Page<Job>>
const jobs = paginate(fetchJobs) // AsyncGenerator<Job, void, unknown>

T is inferred from fetchJobs, so jobs yields Job. The next page is requested only after the caller has taken every item of the current one. Stop reading and the remaining pages are never fetched.

Write take, chunk, paginate and collect. The starter returns arrays and paginate loads every page up front, so the laziness tests and the type tests fail. The tests count the calls a fake fetchPage receives.

  • Iterable<T> is what for...of and spread accept. Take it instead of T[] in helpers.
  • function* returns Generator<T, TReturn, TNext>. T is the yielded type.
  • Generators are lazy: nothing runs until next(), so they can be infinite.
  • async function* returns AsyncGenerator<T>, read with for await.
  • Generic helpers like take, chunk and paginate infer T from their input.