Js iterator pattern

From Intense-Visions/harness-engineering · View interactive version

Js iterator pattern is an AI agent skill from the GitHub repository Intense-Visions/harness-engineering. > Traverse a collection sequentially without exposing its internal structure

How to use this skill

Skill file

JS Iterator Pattern

Traverse a collection sequentially without exposing its internal structure

When to Use

Instructions

  1. Implement the iterator protocol: an object with a next() method returning { value, done }.
  2. Make a collection iterable by adding [Symbol.iterator]() that returns an iterator.
  3. Use generator functions (function*) for the cleanest iterator implementation.
  4. Use for...of to consume iterables.
class Range {
  constructor(start, end) {
    this.start = start;
    this.end = end;
  }

  [Symbol.iterator]() {
    let current = this.start;
    const end = this.end;
    return {
      next() {
        return current <= end
          ? { value: current++, done: false }
          : { value: undefined, done: true };
      },
    };
  }
}

for (const n of new Range(1, 3)) {
  console.log(n); // 1, 2, 3
}
  1. Generator shorthand: *[Symbol.iterator]() { for (let i = this.start; i <= this.end; i++) yield i; }.

Details

JavaScript has a built-in iteration protocol. Any object with a [Symbol.iterator]() method is iterable and works with for...of, spread (...), destructuring, Array.from(), and Promise.all(). Generators (function*) are the simplest way to create custom iterators.

Trade-offs:

When NOT to use:

Source

https://patterns.dev/javascript/iterator-pattern

Process

  1. Read the instructions and examples in this document.
  2. Apply the patterns to your implementation, adapting to your specific context.
  3. Verify your implementation against the details and edge cases listed above.

Harness Integration

Success Criteria

Use this skill with your AI agent: Open on Skill Issue to copy, download, or add to your library. Works with Claude, ChatGPT, Gemini, Cursor, Windsurf and more.