Js state pattern

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

Js state pattern is an AI agent skill from the GitHub repository Intense-Visions/harness-engineering. > Allow an object to alter its behavior when its internal state changes

How to use this skill

Skill file

JS State Pattern

Allow an object to alter its behavior when its internal state changes

When to Use

Instructions

  1. Define a state interface with the actions the context can perform.
  2. Implement one concrete state class per state.
  3. The context delegates behavior to the current state object.
  4. States transition the context by calling context.setState(newState).
class TrafficLight {
  constructor() {
    this.state = new RedState(this);
  }
  setState(state) {
    this.state = state;
  }
  signal() {
    this.state.signal();
  }
}

class RedState {
  constructor(light) {
    this.light = light;
  }
  signal() {
    console.log('Red — stop');
    this.light.setState(new GreenState(this.light));
  }
}

class GreenState {
  constructor(light) {
    this.light = light;
  }
  signal() {
    console.log('Green — go');
    this.light.setState(new RedState(this.light));
  }
}

const light = new TrafficLight();
light.signal(); // Red — stop
light.signal(); // Green — go

Details

The State pattern encapsulates state-dependent behavior into separate classes. The context object delegates to the current state, and states handle transitions. This eliminates complex conditionals and makes adding new states straightforward.

Trade-offs:

When NOT to use:

Source

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