iterator
Traverse elements of a collection without exposing its internal representation.
SKILL.mdskills/code-quality/iterator/SKILL.md
GitHubIterator
Provides a uniform way to sequentially access elements of a collection regardless of how the collection is structured (array, tree, graph, etc.).
When to Use
- You want to hide the internal structure of a collection from consumers
- Multiple traversal algorithms must be supported for the same collection
- A unified interface is needed across different collection types
- Lazy / infinite sequences (generate elements on demand)
How to Apply
- Define an
Iteratorinterface withhasNext()andnext()methods - Define an
Iterableinterface withcreateIterator()returning anIterator - Implement concrete iterator classes (one per traversal strategy or collection type)
- The collection implements
Iterableand returns the appropriate iterator - In modern languages, implement the language's native iterable protocol (
Symbol.iterator,__iter__)
Example
class Range {
constructor(private start: number, private end: number) {}
[Symbol.iterator](): Iterator<number> {
let current = this.start;
const end = this.end;
return {
next(): IteratorResult<number> {
return current <= end
? { value: current++, done: false }
: { value: undefined as any, done: true };
},
};
}
}
for (const n of new Range(1, 5)) {
console.log(n); // 1 2 3 4 5
}