pattern/gof/interpreter
Interpreter
Representa uma gramática como uma árvore de objetos em que cada nó sabe se avaliar (interpret). Use quando regras mudam com frequência e cabem numa linguagem pequena.
- passos
- 4
- arquivos
- 4
- testes
- 0
- tecnologias
- 2
Cenário
O time de fraude escreve regras como texto (hour < 6 and country != BR); o motor as interpreta em cada transação e bloqueia quem casa com alguma, sem deploy para mudar regra.
Planta
Fluxo5 passos — reproduza para seguir o fluxo
- chamada
- resposta ou assíncrono
- falha
- passo
- toque num nó para focar
- Outras plantas de fluxo
Como funciona
4passos
Representa uma gramática como uma árvore de objetos em que cada nó sabe se avaliar (interpret)
Esconde cada passo: lembre antes de tocar para revelar.
Vocabulário compartilhado
or+1
and+1
- 1
ExpressionCompareé a expressão terminal: campo, operador e literal - 2
ExpressionAndeExpressionOrcombinam outras expressões - 3
ruleParsemonta a árvore pela gramática (ortem menor precedência queand) - 4
interpret(transaction)percorre a árvore e devolve se a regra casou
Trade-offs
O que se ganha, o que se paga
Vantagens
Regra nova é texto, sem deploy
Cada nó é testável sozinho
Custos
Gramática grande vira árvore difícil de manter (use um parser real)
Interpretar árvore é mais lento que código compilado
Código
pattern/gof/interpreter
4 arquivos./
- package.jsoninfra
- README.md
- tsconfig.jsoninfra
src/
- demo.tsdemo
Executar só Bun
bun install# dependênciasbun run demo# roda o cenário
Saída: R$ 850,00 às 3h na Nigéria bloqueia por night-abroad, R$ 7.200,00 em aparelho novo bloqueia por big-new-device e R$ 320,00 é aprovado.
- Requisitos
- Bun
Código
src/demo.ts
// Demo: the fraud team writes rules in a tiny language; each rule becomes a tree of expression objects that interprets itself against a transaction.
type Transaction = { amountCents: number; hour: number; country: string; newDevice: boolean };
type Value = number | string | boolean;
interface InterfaceExpression {
interpret(transaction: Transaction): boolean;
}
// Terminal expression: one comparison between a transaction field and a literal.
class ExpressionCompare implements InterfaceExpression {
constructor(private readonly field: keyof Transaction, private readonly operator: string, private readonly literal: Value) {}
interpret(transaction: Transaction): boolean {
const actual = transaction[this.field];
switch (this.operator) {
case ">": return actual > this.literal;
case "<": return actual < this.literal;
case "=": return actual === this.literal;
case "!=": return actual !== this.literal;
default: throw new Error(`unknown operator ${this.operator}`);
}
}
}
// Non-terminal expressions: built from other expressions, so any rule is a tree.
class ExpressionAnd implements InterfaceExpression {
constructor(private readonly left: InterfaceExpression, private readonly right: InterfaceExpression) {}
interpret = (transaction: Transaction) => this.left.interpret(transaction) && this.right.interpret(transaction);
}
class ExpressionOr implements InterfaceExpression {
constructor(private readonly left: InterfaceExpression, private readonly right: InterfaceExpression) {}
interpret = (transaction: Transaction) => this.left.interpret(transaction) || this.right.interpret(transaction);
}
// Grammar: rule := term ("or" term)* ; term := compare ("and" compare)* ; compare := field operator literal.
const FIELDS = new Set(["amountCents", "hour", "country", "newDevice"]);
const literalParse = (token: string): Value => (token === "true" ? true : token === "false" ? false : Number.isNaN(Number(token)) ? token : Number(token));
function compareParse(tokens: string[]): InterfaceExpression {
const [field = "", operator = "", literal = ""] = tokens.splice(0, 3);
if (!FIELDS.has(field)) throw new Error(`unknown field ${field}`);
return new ExpressionCompare(field as keyof Transaction, operator, literalParse(literal));
}
function termParse(tokens: string[]): InterfaceExpression {
let expression = compareParse(tokens);
while (tokens[0] === "and") {
tokens.shift();
expression = new ExpressionAnd(expression, compareParse(tokens));
}
return expression;
}
function ruleParse(text: string): InterfaceExpression {
const tokens = text.trim().split(/\s+/);
let expression = termParse(tokens);
while (tokens[0] === "or") {
tokens.shift();
expression = new ExpressionOr(expression, termParse(tokens));
}
return expression;
}
// Rules are data: the fraud team changes them without a deploy of the engine.
const RULES = {
"night-abroad": "hour < 6 and country != BR",
"big-new-device": "amountCents > 500000 and newDevice = true or amountCents > 2000000",
};
const compiled = Object.entries(RULES).map(([name, text]) => ({ name, text, expression: ruleParse(text) }));
for (const transaction of [
{ amountCents: 85_000, hour: 3, country: "NG", newDevice: false },
{ amountCents: 720_000, hour: 14, country: "BR", newDevice: true },
{ amountCents: 32_000, hour: 10, country: "BR", newDevice: false },
] satisfies Transaction[]) {
const hits = compiled.filter((rule) => rule.expression.interpret(transaction)).map((rule) => rule.name);
console.log(` [FRAUD] R$ ${(transaction.amountCents / 100).toFixed(2)} ${transaction.hour}h ${transaction.country} newDevice=${transaction.newDevice} → ${hits.length ? `BLOCK (${hits.join(", ")})` : "APPROVE"}`);
}
Nível
introdutório
1/13
- Linhas de TypeScript
- 68
- Tipo
- A — código puro
Domínio financeiro
- Antifraude
Padrões do catálogo que implementa
- Interpreter
Trilhapasso 3 de 11
GoF — comportamento
Por que se relacionam
Seu progresso
0/157 estudados
Fica salvo só neste navegador.