Js flyweight pattern

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

Js flyweight pattern is an AI agent skill from the GitHub repository Intense-Visions/harness-engineering. > Share common state across many fine-grained objects to reduce memory usage

How to use this skill

Skill file

JS Flyweight Pattern

Share common state across many fine-grained objects to reduce memory usage

When to Use

Instructions

  1. Separate intrinsic state (shared, immutable) from extrinsic state (unique per instance).
  2. Store intrinsic state in a factory/cache indexed by a key.
  3. Pass extrinsic state as parameters to methods rather than storing it on the flyweight.
  4. Use a FlyweightFactory with a Map to return cached instances.
class BookFlyweight {
  constructor(title, author) {
    this.title = title; // intrinsic — shared
    this.author = author; // intrinsic — shared
  }
}

class BookFactory {
  constructor() {
    this._books = new Map();
  }

  getBook(title, author) {
    const key = `${title}-${author}`;
    if (!this._books.has(key)) {
      this._books.set(key, new BookFlyweight(title, author));
    }
    return this._books.get(key);
  }
}

const factory = new BookFactory();
const b1 = factory.getBook('JS Patterns', 'Stoyan');
const b2 = factory.getBook('JS Patterns', 'Stoyan');
console.log(b1 === b2); // true — same instance

Details

The Flyweight pattern is a structural memory optimization. It trades CPU time (factory lookup) for memory savings by sharing object instances. JavaScript's garbage collector normally handles short-lived objects efficiently, so Flyweight is only necessary at extreme scale.

Trade-offs:

When NOT to use:

Source

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