Js factory pattern

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

Js factory pattern is an AI agent skill from the GitHub repository Intense-Visions/harness-engineering. > Create objects via a factory function without exposing instantiation logic to callers

How to use this skill

Skill file

JS Factory Pattern

Create objects via a factory function without exposing instantiation logic to callers

When to Use

Instructions

  1. Write a factory function (or static class method) that accepts configuration and returns the correct object.
  2. The caller never uses new directly — they call the factory.
  3. Validate inputs inside the factory before creating the object.
  4. Return a consistent interface regardless of which concrete type was created.
function createUser(type, name) {
  const roles = {
    admin: { permissions: ['read', 'write', 'delete'] },
    editor: { permissions: ['read', 'write'] },
    viewer: { permissions: ['read'] },
  };

  if (!roles[type]) throw new Error(`Unknown user type: ${type}`);

  return {
    name,
    type,
    ...roles[type],
    greet() {
      return `Hi, I'm ${name} (${type})`;
    },
  };
}

const admin = createUser('admin', 'Alice');
console.log(admin.permissions); // ['read', 'write', 'delete']

Details

The Factory pattern is one of the most common patterns in JavaScript. Unlike new ClassName(), a factory function can return different types, apply caching, run validation, or perform async initialization.

Trade-offs:

When NOT to use:

Source

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