---
name: iterator
description: This skill should be used when the user asks about "iterator pattern", "when to use iterator", "implement iterator", "traverse collection", "iterable", or mentions needing to access elements sequentially without exposing underlying structure.
version: 1.0.0
---

# Iterator Pattern

## What Is It
The Iterator pattern provides a way to access elements of an aggregate object sequentially without exposing its underlying representation. It separates traversal logic from the collection itself.

## When to Use
- **Custom collections** - Traversing trees, graphs, linked lists
- **Multiple traversal modes** - Forward, backward, depth-first, breadth-first
- **Unified interface** - Same way to iterate different collection types
- **Lazy iteration** - Processing elements on-demand
- **Pagination** - Iterating through large datasets in chunks
- **File/stream processing** - Reading lines, records, or chunks

## When NOT to Use
- **Simple arrays** - Built-in iteration is sufficient
- **Single traversal** - Direct access is simpler
- **Performance critical** - Iterator adds overhead
- **Random access needed** - Use indexed access instead

## How to Implement

### Implementation Steps
1. Create an iterator interface with hasNext() and next() methods
2. Create an iterable interface that returns an iterator
3. Concrete iterators implement traversal logic for specific collections
4. Concrete collections return appropriate iterators

### TypeScript Implementation

```typescript
// Iterator interface
interface Iterator<T> {
  hasNext(): boolean;
  next(): T;
  current(): T;
}

// Iterable interface
interface Iterable<T> {
  getIterator(): Iterator<T>;
}

// Concrete iterator
class ArrayIterator<T> implements Iterator<T> {
  private index = 0;

  constructor(private items: T[]) {}

  hasNext(): boolean {
    return this.index < this.items.length;
  }

  next(): T {
    return this.items[this.index++];
  }

  current(): T {
    return this.items[this.index];
  }
}
```

## Code Examples
See `examples/` directory for runnable TypeScript implementations:
- `examples/iterator.ts` - Basic implementation with various collections
- `examples/iterator-advanced.ts` - Real-world example with tree traversal

## Related Patterns
- **Composite** - Iterators often traverse Composite structures
- **Factory Method** - Collections use Factory Method to create iterators
- **Memento** - Can capture iteration state for later resumption
