Js composite pattern

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

Js composite pattern is an AI agent skill from the GitHub repository Intense-Visions/harness-engineering. > Compose objects into tree structures and treat individual objects and composites uniformly

How to use this skill

Skill file

JS Composite Pattern

Compose objects into tree structures and treat individual objects and composites uniformly

When to Use

Instructions

  1. Define a component interface with the operation that both leaves and composites share.
  2. Leaf classes implement the operation directly.
  3. Composite classes hold a collection of children and delegate the operation to each child.
  4. Clients call the operation on any component without checking whether it is a leaf or composite.
class File {
  constructor(name, size) {
    this.name = name;
    this.size = size;
  }
  getSize() {
    return this.size;
  }
}

class Folder {
  constructor(name) {
    this.name = name;
    this.children = [];
  }
  add(child) {
    this.children.push(child);
    return this;
  }
  getSize() {
    return this.children.reduce((sum, child) => sum + child.getSize(), 0);
  }
}

const root = new Folder('src')
  .add(new File('index.js', 120))
  .add(new Folder('utils').add(new File('helpers.js', 80)));
root.getSize(); // 200

Details

The Composite pattern lets you build tree structures where clients do not need to distinguish between leaves and branches. Every node in the tree responds to the same interface, so operations naturally recurse.

Trade-offs:

When NOT to use:

Source

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