← Back to scenarios
ScenarioCatalog DB

Playlist iterator

Expose playlist songs one at a time through a custom iterator.

Problem

A music application must traverse playlist songs sequentially without exposing the playlist's internal storage structure or placing traversal state in client code.

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