BehavioralTypeScriptverifiedVerified

Iterator Pattern in TypeScript

Provides a way to sequentially access elements of a collection without exposing its underlying representation.

How to Implement the Iterator Pattern in TypeScript

1Step 1: Define the Iterator and Iterable interfaces

interface Iterator<T> {
  hasNext(): boolean;
  next(): T;
}

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

2Step 2: Implement the collection and its iterator

class NumberRange implements Iterable<number> {
  constructor(
    private readonly start: number,
    private readonly end: number,
    private readonly step: number = 1
  ) {}

  createIterator(): Iterator<number> {
    return new RangeIterator(this.start, this.end, this.step);
  }
}

class RangeIterator implements Iterator<number> {
  private current: number;

  constructor(
    private start: number,
    private end: number,
    private step: number
  ) {
    this.current = start;
  }

  hasNext(): boolean {
    return this.current <= this.end;
  }

  next(): number {
    if (!this.hasNext()) throw new Error("No more elements");
    const value = this.current;
    this.current += this.step;
    return value;
  }
}

3Step 3: Traverse the range using the iterator

const range = new NumberRange(1, 10, 2);
const iter = range.createIterator();

while (iter.hasNext()) {
  console.log(iter.next()); // 1, 3, 5, 7, 9
}

Iterator Pattern Architecture

hourglass_empty

Rendering diagram...

lightbulb

Iterator Pattern in the Real World

Think of a TV remote control. Whether your playlist is on a Blu-ray disc, a streaming service, or a USB drive, you use the same next and previous buttons to cycle through content. The remote (iterator interface) abstracts away the completely different internal mechanisms each media source uses to retrieve the next item.