← Back to scenarios
ScenarioCatalog DB

Boolean rule interpreter

Interpret boolean conditions against a context object in a simple rules engine.

Problem

A rules engine must represent and evaluate composable boolean conditions against varying contextual data without embedding every rule combination directly in the calling application.

Related patterns

Implementations

Interpreter

TypeScriptApplication

Interpreter in TypeScript

Models a small rule language as expression objects that evaluate a user context to determine access.

TypeScript
type AccessContext = {
  role: string;
  region: string;
};

interface Expression {
  interpret(context: AccessContext): boolean;
}

class RoleExpression implements Expression {
  constructor(private readonly expectedRole: string) {}

  interpret(context: AccessContext) {
    return context.role === this.expectedRole;
  }
}

class RegionExpression implements Expression {
  constructor(private readonly expectedRegion: string) {}

  interpret(context: AccessContext) {
    return context.region === this.expectedRegion;
  }
}

class AndExpression implements Expression {
  constructor(
    private readonly left: Expression,
    private readonly right: Expression,
  ) {}

  interpret(context: AccessContext) {
    return this.left.interpret(context) && this.right.interpret(context);
  }
}

class OrExpression implements Expression {
  constructor(
    private readonly left: Expression,
    private readonly right: Expression,
  ) {}

  interpret(context: AccessContext) {
    return this.left.interpret(context) || this.right.interpret(context);
  }
}

const canManageBilling = new AndExpression(
  new RoleExpression("admin"),
  new RegionExpression("us"),
);

const canViewDashboard = new OrExpression(
  canManageBilling,
  new RoleExpression("analyst"),
);

console.log(
  canViewDashboard.interpret({
    role: "analyst",
    region: "eu",
  }),
);

Associated technologies