Js visitor pattern

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

Js visitor pattern is an AI agent skill from the GitHub repository Intense-Visions/harness-engineering. > Add new operations to object structures without modifying the objects

How to use this skill

Skill file

JS Visitor Pattern

Add new operations to object structures without modifying the objects

When to Use

Instructions

  1. Define an accept(visitor) method on each element class in the object structure.
  2. Each accept calls the visitor's corresponding method, passing this (double dispatch).
  3. Create visitor objects with one method per element type (e.g., visitFile, visitFolder).
  4. New operations = new visitor objects, without modifying element classes.
class File {
  constructor(name, size) {
    this.name = name;
    this.size = size;
  }
  accept(visitor) {
    return visitor.visitFile(this);
  }
}

class Folder {
  constructor(name, children) {
    this.name = name;
    this.children = children;
  }
  accept(visitor) {
    return visitor.visitFolder(this);
  }
}

const sizeCalculator = {
  visitFile(file) {
    return file.size;
  },
  visitFolder(folder) {
    return folder.children.reduce((sum, child) => sum + child.accept(this), 0);
  },
};
  1. For functional style, use a switch on type tags instead of double dispatch.

Details

The Visitor pattern achieves the open/closed principle by separating operations from the object structure. New operations (visitors) can be added without modifying existing element classes. This is heavily used in compilers and AST processors (e.g., Babel plugins are visitors).

Trade-offs:

When NOT to use:

Source

https://patterns.dev/javascript/visitor-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.