Iterator Pattern

Definition

Provide a way to access the elements of an aggregate object sequentially without exposing its underlying representation.

Explanation

In object-oriented programming, the iterator pattern is a design pattern in which an iterator is used to traverse a container and access the container’s elements. The iterator pattern decouples algorithms from containers; in some cases, algorithms are necessarily container-specific and thus cannot be decoupled.

Iterators that traverse all elements of a container, very often, form the base for more specific Iterators that allow for filtering. The .NET Framework Linq to Objects is a good example of that.

Screencast

TypeScript Code

module Iterator {
    interface IEnumerable {
        [index: number]: T;
        length: number;
    }

    interface IIterator {
        reset(): void;
        moveNext(): boolean
        current: T;
    }

    export class Enumerator implements IIterator {
        protected _index: number;
        protected _items: IEnumerable;
        protected _max: number;

        constructor(items: IEnumerable) {
            this._items = items;
            this.reset();
        }

        public reset(): void {
            this._index = -1;
            this._max = this._items.length - 1;
        }

        public moveNext(): boolean {
            return (this._index++ < this._max);
        }

        get current(): T {
            if (this._index < 0 || this._index > this._max) {
                throw new Error("Invalid operation.");
            }

            return this._items[this._index];
        }
    }


    window.addEventListener("load", function () {
        var persons = new Array("Wesley", "Norbert", "Sam", "Sridhar");
        var h2Nodes = document.getElementsByTagName("h2");

        Output.WriteLine("Iterating through the array.");
        var enumerator = new Enumerator(persons);
        while (enumerator.moveNext()) {
            Output.WriteLine(enumerator.current);
        }

        Output.WriteLine("Iterating through a NodeListOf<HTMLHeadingElement>.");
        var nodesEnumerator = new Enumerator(h2Nodes);
        while (nodesEnumerator.moveNext()) {
            Output.WriteLine(nodesEnumerator.current.textContent);
        }
    });
}

Output