← Back to scenarios
ScenarioCatalog DB

Tree traversal iterator

Traverse a tree in order without exposing its internal node structure.

Problem

A client must traverse a tree in a defined order without depending on node links, recursion details, or the internal representation of the tree.

Related patterns

Implementations

Iterator

TypeScriptApplication

Iterator in TypeScript

Exposes sequential traversal of a paginated result collection while keeping the collection’s storage details private.

TypeScript
type SearchResult = {
  id: string;
  title: string;
};

class SearchResults implements Iterable<SearchResult> {
  constructor(private readonly results: SearchResult[]) {}

  *[Symbol.iterator](): Iterator<SearchResult> {
    for (const result of this.results) {
      yield result;
    }
  }
}

const results = new SearchResults([
  { id: "result-1", title: "Architecture overview" },
  { id: "result-2", title: "Deployment guide" },
  { id: "result-3", title: "Incident playbook" },
]);

for (const result of results) {
  console.log(`${result.id}: ${result.title}`);
}

Associated technologies