{"id":"6b093dc191bd8fbaf2a0c8d4","slug":"paged-results-iterator","title":"Lazy iterator over a paged API","summary":"Orders from an API that returns pages with a cursor, exposed as one collection – lazy page fetching, skipping empty pages, protection against a looping cursor and the native iteration protocol of every language.","servedLang":"en","availableLangs":["pl","en"],"kind":"code","category":"pattern","status":"published","difficulty":"medium","topics":["iterator"],"techs":["typescript","javascript","python","dotnet","java","go"],"tags":["iterator","pagination","lazy-evaluation","generators","behavioral"],"languages":[{"lang":"typescript","runner":"browser","starter":"interface Page<T> {\n  items: T[];\n  /** null = this was the last page. */\n  nextCursor: string | null;\n}\n\n/** Calls the API: null asks for the first page. */\ntype FetchPage<T> = (cursor: string | null) => Page<T>;\n\n/**\n * All items of a paged API as one iterable collection (for...of, spread, Array.from).\n * - lazy: nothing is fetched until the first item is requested, the next page only when the current one runs out;\n * - empty pages are skipped (their nextCursor is still followed);\n * - every iteration starts from the first page;\n * - a cursor used twice in one iteration → Error('Cursor repeated: <cursor>') when it is about to be fetched.\n */\nclass PagedCollection<T> implements Iterable<T> {\n  constructor(private readonly fetchPage: FetchPage<T>) {}\n\n  [Symbol.iterator](): Iterator<T> {\n    // TODO (a generator method `*[Symbol.iterator]()` is fine)\n    throw new Error('Not implemented');\n  }\n}\n","testCount":8,"tests":"const ORDER_PAGES = {\n  first: { items: ['A-1', 'A-2'], nextCursor: 'p2' },\n  p2: { items: ['A-3', 'A-4'], nextCursor: 'p3' },\n  p3: { items: ['A-5'], nextCursor: null },\n};\n\nfunction fakeApi(pages) {\n  const api = {\n    calls: [],\n    fetch: (cursor) => {\n      api.calls.push(cursor);\n      const page = pages[cursor === null ? 'first' : cursor];\n      if (!page) throw new Error('Bad cursor: ' + cursor);\n      return page;\n    },\n  };\n  return api;\n}\n\ntest('iterates over all items of all pages in order', () => {\n  const api = fakeApi(ORDER_PAGES);\n  expect([...new PagedCollection(api.fetch)]).toEqual(['A-1', 'A-2', 'A-3', 'A-4', 'A-5']);\n  expect(api.calls).toEqual([null, 'p2', 'p3']);\n});\n\ntest('nothing is fetched until the first item is requested', () => {\n  const api = fakeApi(ORDER_PAGES);\n  const iterator = new PagedCollection(api.fetch)[Symbol.iterator]();\n  expect(api.calls).toEqual([]);\n  expect(iterator.next()).toEqual({ value: 'A-1', done: false });\n  expect(api.calls).toEqual([null]);\n});\n\ntest('the next page is fetched only when the current one runs out', () => {\n  const api = fakeApi(ORDER_PAGES);\n  const iterator = new PagedCollection(api.fetch)[Symbol.iterator]();\n  iterator.next();\n  iterator.next();\n  expect(api.calls).toEqual([null]);\n  expect(iterator.next().value).toBe('A-3');\n  expect(api.calls).toEqual([null, 'p2']);\n});\n\ntest('stopping early does not fetch further pages', () => {\n  const api = fakeApi(ORDER_PAGES);\n  const taken = [];\n  for (const id of new PagedCollection(api.fetch)) {\n    taken.push(id);\n    if (taken.length === 3) break;\n  }\n  expect(taken).toEqual(['A-1', 'A-2', 'A-3']);\n  expect(api.calls).toEqual([null, 'p2']);\n});\n\ntest('empty pages are skipped and an empty result yields nothing', () => {\n  const sparse = fakeApi({\n    first: { items: [], nextCursor: 'p2' },\n    p2: { items: ['X'], nextCursor: 'p3' },\n    p3: { items: [], nextCursor: null },\n  });\n  expect(Array.from(new PagedCollection(sparse.fetch))).toEqual(['X']);\n  const empty = fakeApi({ first: { items: [], nextCursor: null } });\n  expect([...new PagedCollection(empty.fetch)]).toEqual([]);\n});\n\ntest('every iteration starts from the first page', () => {\n  const api = fakeApi(ORDER_PAGES);\n  const orders = new PagedCollection(api.fetch);\n  expect([...orders]).toHaveLength(5);\n  expect([...orders]).toHaveLength(5);\n  const a = orders[Symbol.iterator]();\n  const b = orders[Symbol.iterator]();\n  expect(a.next().value).toBe('A-1');\n  expect(b.next().value).toBe('A-1');\n  expect(a.next().value).toBe('A-2');\n});\n\ntest('a failing fetch surfaces when that page is reached', () => {\n  const api = fakeApi({ first: ORDER_PAGES.first });\n  const iterator = new PagedCollection(api.fetch)[Symbol.iterator]();\n  expect(iterator.next().value).toBe('A-1');\n  expect(iterator.next().value).toBe('A-2');\n  expect(() => iterator.next()).toThrow('Bad cursor: p2');\n});\n\ntest('a repeated cursor stops the iteration instead of looping forever', () => {\n  const api = fakeApi({\n    first: { items: ['1'], nextCursor: 'a' },\n    a: { items: ['2'], nextCursor: 'b' },\n    b: { items: ['3'], nextCursor: 'a' },\n  });\n  const seen = [];\n  expect(() => {\n    for (const item of new PagedCollection(api.fetch)) seen.push(item);\n  }).toThrow('Cursor repeated: a');\n  expect(seen).toEqual(['1', '2', '3']);\n  expect(api.calls).toEqual([null, 'a', 'b']);\n});\n"},{"lang":"javascript","runner":"browser","starter":"// fetchPage(cursor) calls the API: null asks for the first page; it returns { items: [...], nextCursor: string | null }\n// (nextCursor null = this was the last page).\n\n/**\n * All items of a paged API as one iterable collection (for...of, spread, Array.from).\n * - lazy: nothing is fetched until the first item is requested, the next page only when the current one runs out;\n * - empty pages are skipped (their nextCursor is still followed);\n * - every iteration starts from the first page;\n * - a cursor used twice in one iteration → Error('Cursor repeated: <cursor>') when it is about to be fetched.\n */\nclass PagedCollection {\n  constructor(fetchPage) {\n    this.fetchPage = fetchPage;\n  }\n\n  [Symbol.iterator]() {\n    // TODO (a generator method `*[Symbol.iterator]()` is fine)\n    throw new Error('Not implemented');\n  }\n}\n","testCount":8,"tests":"const ORDER_PAGES = {\n  first: { items: ['A-1', 'A-2'], nextCursor: 'p2' },\n  p2: { items: ['A-3', 'A-4'], nextCursor: 'p3' },\n  p3: { items: ['A-5'], nextCursor: null },\n};\n\nfunction fakeApi(pages) {\n  const api = {\n    calls: [],\n    fetch: (cursor) => {\n      api.calls.push(cursor);\n      const page = pages[cursor === null ? 'first' : cursor];\n      if (!page) throw new Error('Bad cursor: ' + cursor);\n      return page;\n    },\n  };\n  return api;\n}\n\ntest('iterates over all items of all pages in order', () => {\n  const api = fakeApi(ORDER_PAGES);\n  expect([...new PagedCollection(api.fetch)]).toEqual(['A-1', 'A-2', 'A-3', 'A-4', 'A-5']);\n  expect(api.calls).toEqual([null, 'p2', 'p3']);\n});\n\ntest('nothing is fetched until the first item is requested', () => {\n  const api = fakeApi(ORDER_PAGES);\n  const iterator = new PagedCollection(api.fetch)[Symbol.iterator]();\n  expect(api.calls).toEqual([]);\n  expect(iterator.next()).toEqual({ value: 'A-1', done: false });\n  expect(api.calls).toEqual([null]);\n});\n\ntest('the next page is fetched only when the current one runs out', () => {\n  const api = fakeApi(ORDER_PAGES);\n  const iterator = new PagedCollection(api.fetch)[Symbol.iterator]();\n  iterator.next();\n  iterator.next();\n  expect(api.calls).toEqual([null]);\n  expect(iterator.next().value).toBe('A-3');\n  expect(api.calls).toEqual([null, 'p2']);\n});\n\ntest('stopping early does not fetch further pages', () => {\n  const api = fakeApi(ORDER_PAGES);\n  const taken = [];\n  for (const id of new PagedCollection(api.fetch)) {\n    taken.push(id);\n    if (taken.length === 3) break;\n  }\n  expect(taken).toEqual(['A-1', 'A-2', 'A-3']);\n  expect(api.calls).toEqual([null, 'p2']);\n});\n\ntest('empty pages are skipped and an empty result yields nothing', () => {\n  const sparse = fakeApi({\n    first: { items: [], nextCursor: 'p2' },\n    p2: { items: ['X'], nextCursor: 'p3' },\n    p3: { items: [], nextCursor: null },\n  });\n  expect(Array.from(new PagedCollection(sparse.fetch))).toEqual(['X']);\n  const empty = fakeApi({ first: { items: [], nextCursor: null } });\n  expect([...new PagedCollection(empty.fetch)]).toEqual([]);\n});\n\ntest('every iteration starts from the first page', () => {\n  const api = fakeApi(ORDER_PAGES);\n  const orders = new PagedCollection(api.fetch);\n  expect([...orders]).toHaveLength(5);\n  expect([...orders]).toHaveLength(5);\n  const a = orders[Symbol.iterator]();\n  const b = orders[Symbol.iterator]();\n  expect(a.next().value).toBe('A-1');\n  expect(b.next().value).toBe('A-1');\n  expect(a.next().value).toBe('A-2');\n});\n\ntest('a failing fetch surfaces when that page is reached', () => {\n  const api = fakeApi({ first: ORDER_PAGES.first });\n  const iterator = new PagedCollection(api.fetch)[Symbol.iterator]();\n  expect(iterator.next().value).toBe('A-1');\n  expect(iterator.next().value).toBe('A-2');\n  expect(() => iterator.next()).toThrow('Bad cursor: p2');\n});\n\ntest('a repeated cursor stops the iteration instead of looping forever', () => {\n  const api = fakeApi({\n    first: { items: ['1'], nextCursor: 'a' },\n    a: { items: ['2'], nextCursor: 'b' },\n    b: { items: ['3'], nextCursor: 'a' },\n  });\n  const seen = [];\n  expect(() => {\n    for (const item of new PagedCollection(api.fetch)) seen.push(item);\n  }).toThrow('Cursor repeated: a');\n  expect(seen).toEqual(['1', '2', '3']);\n  expect(api.calls).toEqual([null, 'a', 'b']);\n});\n"},{"lang":"python","runner":"browser","starter":"from dataclasses import dataclass, field\nfrom typing import Callable, Iterator\n\n\n@dataclass\nclass Page:\n    items: list = field(default_factory=list)\n    next_cursor: str | None = None  # None = this was the last page\n\n\nclass PagedCollection:\n    \"\"\"All items of a paged API as one iterable collection (for, list(), next(iter(...))).\n    fetch_page(cursor) calls the API; None asks for the first page.\n    - lazy: nothing is fetched until the first item is requested, the next page only when the current one runs out;\n    - empty pages are skipped (their next_cursor is still followed);\n    - every iteration starts from the first page;\n    - a cursor used twice in one iteration → RuntimeError('Cursor repeated: <cursor>') when it is about to be fetched.\"\"\"\n\n    def __init__(self, fetch_page: Callable[[str | None], Page]):\n        self.fetch_page = fetch_page\n\n    def __iter__(self) -> Iterator:\n        raise NotImplementedError  # TODO (a generator with `yield` is fine)\n","testCount":8,"tests":"ORDER_PAGES = {\n    None: Page([\"A-1\", \"A-2\"], \"p2\"),\n    \"p2\": Page([\"A-3\", \"A-4\"], \"p3\"),\n    \"p3\": Page([\"A-5\"], None),\n}\n\n\nclass FakeApi:\n    def __init__(self, pages):\n        self.pages = pages\n        self.calls = []\n\n    def fetch(self, cursor):\n        self.calls.append(cursor)\n        if cursor not in self.pages:\n            raise LookupError(f\"Bad cursor: {cursor}\")\n        return self.pages[cursor]\n\n\ndef test_iterates_over_all_items_of_all_pages_in_order():\n    api = FakeApi(ORDER_PAGES)\n    got = list(PagedCollection(api.fetch))\n    assert got == [\"A-1\", \"A-2\", \"A-3\", \"A-4\", \"A-5\"], f\"got {got}\"\n    assert api.calls == [None, \"p2\", \"p3\"], f\"got calls {api.calls}\"\n\n\ndef test_nothing_is_fetched_until_the_first_item_is_requested():\n    api = FakeApi(ORDER_PAGES)\n    iterator = iter(PagedCollection(api.fetch))\n    assert api.calls == [], f\"fetched too early: {api.calls}\"\n    assert next(iterator) == \"A-1\"\n    assert api.calls == [None], f\"got calls {api.calls}\"\n\n\ndef test_the_next_page_is_fetched_only_when_the_current_one_runs_out():\n    api = FakeApi(ORDER_PAGES)\n    iterator = iter(PagedCollection(api.fetch))\n    next(iterator)\n    next(iterator)\n    assert api.calls == [None], f\"got calls {api.calls}\"\n    assert next(iterator) == \"A-3\"\n    assert api.calls == [None, \"p2\"], f\"got calls {api.calls}\"\n\n\ndef test_stopping_early_does_not_fetch_further_pages():\n    api = FakeApi(ORDER_PAGES)\n    taken = []\n    for order_id in PagedCollection(api.fetch):\n        taken.append(order_id)\n        if len(taken) == 3:\n            break\n    assert taken == [\"A-1\", \"A-2\", \"A-3\"]\n    assert api.calls == [None, \"p2\"], f\"got calls {api.calls}\"\n\n\ndef test_empty_pages_are_skipped_and_an_empty_result_yields_nothing():\n    sparse = FakeApi({None: Page([], \"p2\"), \"p2\": Page([\"X\"], \"p3\"), \"p3\": Page([], None)})\n    assert list(PagedCollection(sparse.fetch)) == [\"X\"]\n    empty = FakeApi({None: Page([], None)})\n    assert list(PagedCollection(empty.fetch)) == []\n    iterator = iter(PagedCollection(empty.fetch))\n    with raises(StopIteration):\n        next(iterator)\n\n\ndef test_every_iteration_starts_from_the_first_page():\n    api = FakeApi(ORDER_PAGES)\n    orders = PagedCollection(api.fetch)\n    assert len(list(orders)) == 5\n    assert len(list(orders)) == 5\n    a, b = iter(orders), iter(orders)\n    assert next(a) == \"A-1\"\n    assert next(b) == \"A-1\"\n    assert next(a) == \"A-2\"\n\n\ndef test_a_failing_fetch_surfaces_when_that_page_is_reached():\n    api = FakeApi({None: ORDER_PAGES[None]})\n    iterator = iter(PagedCollection(api.fetch))\n    assert next(iterator) == \"A-1\"\n    assert next(iterator) == \"A-2\"\n    with raises(LookupError, match=\"Bad cursor: p2\"):\n        next(iterator)\n\n\ndef test_a_repeated_cursor_stops_the_iteration_instead_of_looping_forever():\n    api = FakeApi({None: Page([\"1\"], \"a\"), \"a\": Page([\"2\"], \"b\"), \"b\": Page([\"3\"], \"a\")})\n    seen = []\n    with raises(RuntimeError, match=\"Cursor repeated: a\"):\n        for item in PagedCollection(api.fetch):\n            seen.append(item)\n    assert seen == [\"1\", \"2\", \"3\"], f\"got {seen}\"\n    assert api.calls == [None, \"a\", \"b\"], f\"got calls {api.calls}\"\n"},{"lang":"csharp","runner":"judge0","starter":"using System;\nusing System.Collections;\nusing System.Collections.Generic;\n\npublic sealed class Page<T>\n{\n    public Page(IReadOnlyList<T> items, string nextCursor)\n    {\n        Items = items;\n        NextCursor = nextCursor;\n    }\n\n    public IReadOnlyList<T> Items { get; }\n    public string NextCursor { get; } // null = this was the last page\n}\n\n/// <summary>\n/// All items of a paged API as one IEnumerable (foreach, LINQ). fetchPage(null) asks for the first page.\n/// - lazy: nothing is fetched until the first item is requested, the next page only when the current one runs out;\n/// - empty pages are skipped (their NextCursor is still followed);\n/// - every enumeration starts from the first page;\n/// - a cursor used twice in one enumeration → InvalidOperationException(\"Cursor repeated: c\") when it is about to be fetched.\n/// </summary>\npublic class PagedCollection<T> : IEnumerable<T>\n{\n    private readonly Func<string, Page<T>> fetchPage;\n\n    public PagedCollection(Func<string, Page<T>> fetchPage)\n    {\n        this.fetchPage = fetchPage;\n    }\n\n    public IEnumerator<T> GetEnumerator()\n    {\n        // TODO (an iterator method with yield return is fine)\n        throw new NotImplementedException();\n    }\n\n    IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); }\n}\n","testCount":8},{"lang":"java","runner":"judge0","starter":"import java.util.Iterator;\nimport java.util.List;\nimport java.util.function.Function;\n\nfinal class Page<T> {\n    final List<T> items;\n    final String nextCursor; // null = this was the last page\n\n    Page(List<T> items, String nextCursor) {\n        this.items = items;\n        this.nextCursor = nextCursor;\n    }\n}\n\n/**\n * All items of a paged API as one Iterable (enhanced for loop). fetchPage.apply(null) asks for the first page.\n * - lazy: nothing is fetched until the first item is requested, the next page only when the current one runs out;\n * - empty pages are skipped (their nextCursor is still followed);\n * - every iteration starts from the first page; next() after the end → NoSuchElementException;\n * - a cursor used twice in one iteration → IllegalStateException(\"Cursor repeated: c\") when it is about to be fetched.\n */\nclass PagedCollection<T> implements Iterable<T> {\n    private final Function<String, Page<T>> fetchPage;\n\n    PagedCollection(Function<String, Page<T>> fetchPage) {\n        this.fetchPage = fetchPage;\n    }\n\n    @Override\n    public Iterator<T> iterator() {\n        // TODO: return a new Iterator<T> (an inner class with hasNext() / next())\n        throw new UnsupportedOperationException(\"Not implemented\");\n    }\n}\n","testCount":8},{"lang":"go","runner":"judge0","starter":"package main\n\n// Page is one page of results; NextCursor \"\" means this was the last page.\ntype Page struct {\n\tItems      []string\n\tNextCursor string\n}\n\n// FetchFunc calls the API; the cursor \"\" asks for the first page.\ntype FetchFunc func(cursor string) (Page, error)\n\n// PageIterator walks over all items of all pages, in the style of bufio.Scanner and sql.Rows:\n//\n//\tfor it.Next() { use(it.Value()) }\n//\tif err := it.Err(); err != nil { ... }\n//\n// - lazy: nothing is fetched until the first Next, the next page only when the current one runs out;\n// - empty pages are skipped (their NextCursor is still followed);\n// - a fetch error stops the iteration and is returned by Err;\n// - a cursor used twice → Err() == \"cursor repeated: <cursor>\" (checked when it is about to be fetched).\ntype PageIterator struct {\n\tfetch FetchFunc\n\t// TODO: position, current page items, cursor, used cursors, current value, error\n}\n\n// NewPageIterator does not fetch anything yet.\nfunc NewPageIterator(fetch FetchFunc) *PageIterator {\n\treturn &PageIterator{fetch: fetch}\n}\n\n// Next advances to the next item; false when there are no more items or an error occurred.\nfunc (it *PageIterator) Next() bool {\n\t// TODO\n\treturn false\n}\n\n// Value is the current item (valid after Next returned true).\nfunc (it *PageIterator) Value() string {\n\t// TODO\n\treturn \"\"\n}\n\n// Err is the error that stopped the iteration, nil after a normal end.\nfunc (it *PageIterator) Err() error {\n\t// TODO\n\treturn nil\n}\n","testCount":8}],"questionCount":null,"xp":20,"stats":{"attempts":0,"solves":0,"solutions":0,"comments":0},"solveRate":null,"publishedAt":"2026-11-27T08:22:25.658Z","requestedLang":"en","statement":{"type":"doc","content":[{"type":"paragraph","content":[{"type":"text","text":"The payment platform's API returns orders in pages: "},{"type":"text","text":"{ items, nextCursor }","marks":[{"type":"code"}]},{"type":"text","text":", and the next page is fetched by passing the cursor from the previous one. Today every report repeats the same "},{"type":"text","text":"while (cursor)","marks":[{"type":"code"}]},{"type":"text","text":" loop with manual list concatenation – and every now and then someone fetches all 400 pages just to show the first ten rows. "},{"type":"text","text":"Iterator","marks":[{"type":"bold"}]},{"type":"text","text":" hides how a collection is traversed: client code writes an ordinary "},{"type":"text","text":"for","marks":[{"type":"code"}]},{"type":"text","text":", and only the iterator knows about pages."}]},{"type":"heading","attrs":{"level":2,"id":"task"},"content":[{"type":"text","text":"Task"}]},{"type":"paragraph","content":[{"type":"text","text":"The collection ("},{"type":"text","text":"PagedCollection","marks":[{"type":"code"}]},{"type":"text","text":", in Go "},{"type":"text","text":"PageIterator","marks":[{"type":"code"}]},{"type":"text","text":") receives a "},{"type":"text","text":"fetchPage(cursor)","marks":[{"type":"code"}]},{"type":"text","text":" function that returns the first page for an empty cursor ("},{"type":"text","text":"null","marks":[{"type":"code"}]},{"type":"text","text":"/"},{"type":"text","text":"None","marks":[{"type":"code"}]},{"type":"text","text":"/"},{"type":"text","text":"\"\"","marks":[{"type":"code"}]},{"type":"text","text":"). Requirements:"}]},{"type":"orderedList","attrs":{"start":1},"content":[{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"The native iteration protocol","marks":[{"type":"bold"}]},{"type":"text","text":" of each language:"}]},{"type":"bulletList","content":[{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"TypeScript/JavaScript – "},{"type":"text","text":"[Symbol.iterator]()","marks":[{"type":"code"}]},{"type":"text","text":" (so "},{"type":"text","text":"for...of","marks":[{"type":"code"}]},{"type":"text","text":", spread and "},{"type":"text","text":"Array.from","marks":[{"type":"code"}]},{"type":"text","text":" work);"}]}]},{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"Python – "},{"type":"text","text":"__iter__","marks":[{"type":"code"}]},{"type":"text","text":" (so "},{"type":"text","text":"for","marks":[{"type":"code"}]},{"type":"text","text":", "},{"type":"text","text":"list()","marks":[{"type":"code"}]},{"type":"text","text":" and "},{"type":"text","text":"next(iter(...))","marks":[{"type":"code"}]},{"type":"text","text":" work);"}]}]},{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"C# – "},{"type":"text","text":"IEnumerable<T>","marks":[{"type":"code"}]},{"type":"text","text":" (so "},{"type":"text","text":"foreach","marks":[{"type":"code"}]},{"type":"text","text":" and LINQ work);"}]}]},{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"Java – "},{"type":"text","text":"Iterable<T>","marks":[{"type":"code"}]},{"type":"text","text":" with its own "},{"type":"text","text":"Iterator<T>","marks":[{"type":"code"}]},{"type":"text","text":"; "},{"type":"text","text":"next()","marks":[{"type":"code"}]},{"type":"text","text":" past the end throws "},{"type":"text","text":"NoSuchElementException","marks":[{"type":"code"}]},{"type":"text","text":";"}]}]},{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"Go (1.13, no iterators in the language) – the "},{"type":"text","text":"bufio.Scanner","marks":[{"type":"code"}]},{"type":"text","text":" style: "},{"type":"text","text":"for it.Next() { it.Value() }","marks":[{"type":"code"}]},{"type":"text","text":", then "},{"type":"text","text":"it.Err()","marks":[{"type":"code"}]},{"type":"text","text":"."}]}]}]}]},{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"Laziness","marks":[{"type":"bold"}]},{"type":"text","text":" – creating an iterator fetches nothing; the first page is fetched with the first element, the next one only when the current page runs out. Breaking out of the loop after three elements fetches no further pages."}]}]},{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"Empty pages","marks":[{"type":"bold"}]},{"type":"text","text":" are skipped (but their cursor is still followed); an empty result simply has no elements."}]}]},{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"Every iteration starts from the first page","marks":[{"type":"bold"}]},{"type":"text","text":" and has its own state – two iterators over the same collection do not interfere."}]}]},{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"Errors","marks":[{"type":"bold"}]},{"type":"text","text":" – a fetch exception surfaces when that page is reached (in Go: "},{"type":"text","text":"Next()","marks":[{"type":"code"}]},{"type":"text","text":" returns "},{"type":"text","text":"false","marks":[{"type":"code"}]},{"type":"text","text":" and "},{"type":"text","text":"Err()","marks":[{"type":"code"}]},{"type":"text","text":" returns the error). A cursor used a second time in the same iteration ends it with the error "},{"type":"text","text":"Cursor repeated: <cursor>","marks":[{"type":"code"}]},{"type":"text","text":" (in Go "},{"type":"text","text":"cursor repeated: <cursor>","marks":[{"type":"code"}]},{"type":"text","text":"), raised when the cursor is about to be used – elements from earlier pages have already been delivered."}]}]}]}]},"hints":[],"hintsCount":3,"quiz":null,"solutionNotes":null,"unlocked":false,"external":[],"articles":[{"id":"6b08bd3980884893657cc996","slug":"iterator","title":"Iterator: walking a collection without looking inside"},{"id":"6b08bd3180884893657cc91a","slug":"composite","title":"Composite – trees in which a leaf and a branch look the same"}],"topicsInfo":[{"slug":"iterator","title":"Iterator","group":"behavioral","icon":"list-ordered"}],"author":{"id":"6b08bd2e80884893657cc8cf","name":"Redakcja Art of Devs","avatar":null,"handle":"redakcja","community":false},"capabilities":{"judge0":false,"aiReview":false},"createdAt":"2026-11-27T08:22:25.660Z","updatedAt":"2026-11-27T08:22:25.660Z"}