Skip to content
BBaskaran

Iterator

Traverse a collection without exposing its underlying representation.

Use it when

A collection has a complex structure but clients need a simple way to walk it.

/**
 * Iterator: walk through every order without caring that the API returns pages.
 *
 * Real-world scenario: an orders API returns results one page at a time. Client
 * code just wants `for (const order of orders)`. The iterator hides the paging:
 * it fetches the next page only when the current one runs out, so stopping early
 * never downloads pages nobody needs.
 *
 * JavaScript builds this pattern into the language: any object with a
 * [Symbol.iterator]() method works in for...of, and next() hands out one item
 * at a time as { value, done }.
 */

const PAGES = [["ORD-1", "ORD-2", "ORD-3"], ["ORD-4", "ORD-5", "ORD-6"], ["ORD-7"]];

// The underlying data source, with its awkward page-based interface.
class OrdersAPI {
  fetchPage(page: number): string[] {
    console.log(`  (fetching page ${page + 1})`);
    return page < PAGES.length ? [...PAGES[page]] : [];
  }
}

// Iterator: remembers where it is and fetches pages on demand.
class OrderIterator implements Iterator<string> {
  private readonly api: OrdersAPI;
  private page = 0;
  private items: string[] = [];
  private index = 0;

  constructor(api: OrdersAPI) {
    this.api = api;
  }

  next(): IteratorResult<string> {
    if (this.index === this.items.length) {
      // Current page used up: fetch the next one.
      this.items = this.api.fetchPage(this.page);
      this.page += 1;
      this.index = 0;
      if (this.items.length === 0) {
        return { value: undefined, done: true }; // no more pages: the loop ends
      }
    }
    const value = this.items[this.index];
    this.index += 1;
    return { value, done: false };
  }
}

// Collection: hands out a fresh iterator for each loop.
class AllOrders implements Iterable<string> {
  private readonly api: OrdersAPI;

  constructor(api: OrdersAPI) {
    this.api = api;
  }

  [Symbol.iterator](): Iterator<string> {
    return new OrderIterator(this.api);
  }
}

function clientCode(): void {
  const orders = new AllOrders(new OrdersAPI());

  console.log("All orders:");
  for (const order of orders) {
    console.log(order);
  }

  console.log("Find ORD-2 and stop:");
  for (const order of orders) {
    if (order === "ORD-2") {
      console.log(`found ${order}, later pages never fetched`);
      break;
    }
  }
}

clientCode();

// Output:
// All orders:
//   (fetching page 1)
// ORD-1
// ORD-2
// ORD-3
//   (fetching page 2)
// ORD-4
// ORD-5
// ORD-6
//   (fetching page 3)
// ORD-7
//   (fetching page 4)
// Find ORD-2 and stop:
//   (fetching page 1)
// found ORD-2, later pages never fetched

How it works

RoleClassesWhat it does
Data sourceOrdersAPIReturns orders one page at a time: the awkward structure to hide
IteratorOrderIteratornext() returns one order at a time as { value, done }, fetching pages only when needed
CollectionAllOrders[Symbol.iterator]() hands out a fresh iterator, so it works in any for...of loop
ClientclientCode()Just loops over orders; never sees pages